Return and instance of a class given its .class (MyClass.class)

I have an enumeration that will contain my algorithms. I cannot create instances of these classes because I need an application context that is accessible only after the application starts. I want to load the class at runtime when I select by calling getAlgorithm (Context cnx).

How to easily instantiate a class at runtime given its .class (and my constructor accepts arguments)? All my classes are subclasses of the 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);
}

}

+3
source share
2 answers

java.lang.Class<T>It has all the necessary magic, in particular you can use forName()and getConstructor()to get the necessary effect, as shown below:

public Constructor getAlgorithm(Context cnx) {
    Class klass = Class.forName("YourClassName"));
    Constructor constructor = klass.getConstructor(cnx.getClass());
    return constructor;
}

, getAlgorithm , , :

public Algorithm getAlgorithm(Context cnx) {
    Class klass = Class.forName("YourClassName"));
    Constructor constructor = klass.getConstructor(cnx.getClass());
    return constructor.newInstance(ctx);
}
+1

Source: https://habr.com/ru/post/1747143/


All Articles