Returning and instance of a Class given its .class (MyClass.class)
I have an enum that will hold my algorithms. I cannot instantiate these classes because I need the application context which is only available once the application has started. I want to load the class at runtime when I choose by calling getAlgorithm(Context cnx).
How do I easily instantiate a class at runtime given its .class (and my constructor takes arguments)? All my classes are subclasses of Algorithm.
public enum AlgorithmTypes {
ALL_FROM_9_AND_LAST_FROM_10_ID(AlgorithmFactory.AlgorithmAllFrom9AndLastFrom10Impl.class),
ALL_FROM_9_AND_LAST_FROM_10_CURRENCY_ID(AlgorithmFactory.AlgorithmAllFrom9AndLastFrom10Impl.class),
DIVIDE_BY_9_LESS_THAN_100(AlgorithmFactory.AlgorithmAllFrom9AndLastFrom10Impl.class),
TABLES_BEYOND_5_BY_5(AlgorithmFac开发者_开发百科tory.AlgorithmAllFrom9AndLastFrom10Impl.class);
private Class<? extends Algorithm> algorithm;
AlgorithmTypes(Class<? extends Algorithm> c) {
algorithm = c;
}
public Algorithm getAlgorithm(Context cnx) {
return //needs to return the current algoriths constructor which takes the Context Algorithm(Context cnx);
}
}
java.lang.Class<T>
has all the magic you need, in particular you can use the forName()
and getConstructor()
methods to get the effect you want like below:
public Constructor getAlgorithm(Context cnx) {
Class klass = Class.forName("YourClassName"));
Constructor constructor = klass.getConstructor(cnx.getClass());
return constructor;
}
If you want getAlgorithm
to return an instance rather than just the constructor to invoke you can invoke the constructor:
public Algorithm getAlgorithm(Context cnx) {
Class klass = Class.forName("YourClassName"));
Constructor constructor = klass.getConstructor(cnx.getClass());
return constructor.newInstance(ctx);
}
You can use the Class.getConstructor() function in order to obtain the constructor, and then you can use Constructor.newInstance() in order to instantiate the class, while passing arguments to the constructor.
精彩评论