Reputation: 1341
I have the following interface defined:
public interface AllImplementMe<X, Y> {
public Y doSomething(X param);
}
Now I wish to define a factory method which needs to construct sub classes for above at runtime.
public static <X,Y> AllImplementMe<X, Y> createInstance(String xClassName, String yClassName) { ... }
How do I actually code the above method? I've been looking at reflection API but unable to figure it out? It is assumed that all sub classes have a default constructor.
Edit1
I just want to add some clarification regarding the intent of the above code. The above is just a part of generic system which will allow new implementing sub classes to be added at runtime and be executed based on externally defined configuration. So in reality the factory method will be called based on this configuration and construct appropriate child object which will then be asked to execute their methods. This is conceptually similar to the Adnroid's AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html with the problem that I need to construct implementing child class objects in a generic fashion. For most part the core code that will call these children is not concerned with their param types.
Upvotes: 2
Views: 1780
Reputation: 34900
Everything is much simpler. You even do not need these parameters String xClassName, String yClassName
.
Consider you have some implementation of your interface:
public class SomeImplementation<A,B> implements AllImplementMe<A,B> {
@Override
public B doSomething(A param) {
// ... blablabla ...
}
}
Then your static factory method will be just:
public static <A, B> AllImplementMe<A, B> createInstance() {
return new SomeImplementation<A,B>();
}
Upvotes: 1
Reputation: 3241
Use the following factory method instead:
public static <X, Y> AllImplementMe<X, Y> createInstance(Class<X> xClass, Class<Y> yClass)
Then you can use things like xClass.newInstance()
to create an instance of X
. (I haven't written the exact code since I don't know exactly what you want to do with X
and Y
.)
Upvotes: 2