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

Posted by jax on Stack Overflow See other posts from Stack Overflow or by jax
Published on 2010-05-26T07:40:41Z Indexed on 2010/05/26 8:11 UTC
Read the original article Hit count: 185

Filed under:

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

}

© Stack Overflow or respective owner

Related posts about java