All the examples I look at for reflection show creating a new instance of an unknown implementation, and casting that implementation to it’s interface. The issue with this is that now you can’t call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type. Here is what I have:
Class c = null;
try {
c = Class.forName("com.path.to.ImplementationType");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
InterfaceType interfaceType = null;
try {
interfaceType = (InterfaceType)c.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
If I only have a reference to “com.path.to.ImplementationType”, and I don’t know what that type might be (it is coming from a config file), then how can I use the class name to cast it to ImplementationType? Is this even possible?
This line seems to sum up the crux of your problem:
You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:
1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a
Stringequals()test to determine whether your class is of the type that you want, and then perform a hard-coded cast:This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.
2. Another option you have is to extend your reflection from just
Class/Objectcreation to includeMethodreflection. If you can create theClassfrom a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of theMethoditself from yourClassobject. You can then callinvoke(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object…)) on theMethod, passing in the instance of your class that you created. I think this will help you get what you are after.Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their
Classobejcts and instances.and my output: