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(AlgorithmFactory.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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With