Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning and instance of a Class given its .class (MyClass.class)

Tags:

java

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);
}

}

like image 270
jax Avatar asked Feb 01 '26 12:02

jax


1 Answers

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);
}
like image 146
Tendayi Mawushe Avatar answered Feb 03 '26 01:02

Tendayi Mawushe