Re: Do you ever use reflection instead of OO?



Aaron Fude wrote:

The OO alternative would be to create an interface "HTMLable", but the
above approach saves the user from having to implement that on every
type of object that he might want to stick into a table. As another

Well, no.

It's easy in Java to pass interfaces without actually implementing that interface on any object.

public class TestHtml {
public void main( String ... args ) {
Set s = new HashSet();
s.addAll(Arrays.asList(
"one two three four five six seven".split(" ")));

Htmlizer( new HtmlTableIface() {
public String toHtml() {
return "<code>"+s.toString+"</code>";
}
} );

}

void Htmlizer ( HtmlTableIface h ) {
System.out.println( h.toHtml() )
}
}

interface HtmlTableIface {
String toHtml();
}


I didn't compile that, but you get the idea. To pass an object to a method that takes an interface, just wrap the object in an anonymous class. This isn't always the best, but it works for "simple situations."

In general, you want to ensure intent. Require interfaces because it's better to push some of the work off to the caller. In your example, you could simplify your reflection just to this:

print( obj.toString );

And then just provide an appropriate toString method for all objects.

public class MyHtmlTableEntry {
public String toString() {
return "<code>"+...+"</code>";
}
}
.



Relevant Pages

  • Re: Casting Generic Classes - Possible Solution
    ... It leaves me with the open option to use generics or not when I ... This works as saying "accept a store of anything that are Record ... public class Record { ... So I tried adding an interface into the structure: ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Circular Referencing in C#
    ... I used this problem as an interview question about a month ... I configure it using config files. ... put the interface into the base code libraries. ... > public class A1C1 ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: List<> classes and inheritance (C#)
    ... I think the answer to your question is the use of an interface that all ... public class MyClass1: IMyInterface ... There may be no need at all to override the Add method at this point because ...
    (microsoft.public.dotnet.csharp.general)
  • Re: Help with this sample
    ... you could use an interface: ... class Cls1: IReturn ... class Cls2: IReturn ... public class Class1 ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Converting constants-only interfaces to abstract classes
    ... am satisfied that those are good reasons. ... I changed my first interface, ... public class ResumeWriter implements ResumeConstants { ...
    (comp.lang.java.programmer)