I would choose a different approach. Either
- use polymorphism as suggested by others, extend Element to add a print() method (which can be overwritten by sub classes) or
- define a helper interface and use a combination of strategy and factory pattern:
Base Class
public class Element{}
Derived Class
public class SubElement extends Element{}
Helper Interface to print elements
public interface PrintHelper{
void print(Element element);
}
Factory to get the best PrintHelper for a given element
public class PrintHelperFactory{
private final Map<Class<? extends Element>, PrintHelper> registeredHelpers =
new HashMap<Class<? extends Element>, PrintHelper>();
// Register a PrintHelper for a given Element class.
public void registerHelper(final Class<? extends Element> clazz,
final PrintHelper helper){
this.registeredHelpers.put(clazz, helper);
}
// Get the most specific PrintHelper for a given Element.
public PrintHelper getHelperForElement(final Element element){
Class<? extends Element> clazz = element.getClass();
while(!Object.class.equals(clazz)){
if(this.registeredHelpers.containsKey(clazz)){
return this.registeredHelpers.get(clazz);
}
clazz = (Class<? extends Element>) clazz.getSuperclass();
}
return null;
}
}
Client test class, run as Java Application
public class Main{
public static void main(final String[] args){
final PrintHelperFactory factory = new PrintHelperFactory();
factory.registerHelper(Element.class, new PrintHelper(){
@Override
public void print(final Element element){
System.out.println("Element");
}
});
factory.registerHelper(SubElement.class, new PrintHelper(){
@Override
public void print(final Element element){
System.out.println("Sub Element");
}
});
// test it with an Element
final Element elem = new Element();
factory.getHelperForElement(elem).print(elem);
// test it with a sub class
final Element sub = new SubElement();
factory.getHelperForElement(sub).print(sub);
}
}
Output
Element
Sub Element