Reputation: 155
I have a use case with a class existing in 2 versions of a package.
package packageV1;
public class MyClass extends BaseClass{
public static String example(){
return "Version1";
}
}
package packageV2;
public class MyClass extends BaseClass{
public static String example(){
return "Version2";
}
}
So far so good (I believe).
Then I have an application using that class, and to avoid rewriting the application for the different package version, I want to pass the class that should be use (ie for the package of interest) as argument to the application. So something like
public class Application{
private Class<BaseClass> selectedClass;
public void Application(Class<BaseClass> selectedClass){
this.selectedClass = selectedClass;
this.selectedClass.example(); // not possible
}
}
I believe I could call this.selectedClass.example();
if I were passing an instance of MyClass
in the constructor, but then I would call static methods through a instance object, not nice right ?
On the other hand, in the example above selectedClass
is a Class object, so I can't call the static method example
as above.
Does this mean I should use reflection ? like selectedClass.getMethod(name, parameterTypes)
.
Looks overly complicated to me.
Or is there a better design ?
Upvotes: 1
Views: 2148
Reputation: 147154
@javadev is right. Using reflection is almost always a really bad idea. It is that which over complicates.
There is no need for reflection here. The ability to invoke static methods on instances was rapidly realised to be a design error. So much so that there is a subsequent highly unorthogonal design choice in that it does not work for static methods that are members of interfaces.
The simple solution is to move the static methods to instance methods of stateless objects. No Class
, or other reflection, necessary. This is an application of the Strategy design pattern.
Upvotes: 1
Reputation: 790
Using a static method this way is not a good design, and not according to the Object Orinted principles.
My tip is to try changing "example()" to be a regular method, and not static.
Upvotes: 1