3

I try to find a way to do it but i didn't find out, please let me know if my question has already been asked.

Basically i have a generic interface Evaluator<E, T> with a single method E evaluate(T a, T b) which will be implemented by lot of classes (for each Evaluator implementation correspond a specific algorithm). The class which use those evaluators use an XML configuration file which indicate which Evaluator class to use. To get an Evaluator from a given class name i decided to set a EvaluatorProvider class which build a evaluator from a given classe name.

This method is also generic :

public static <E, T> Evaluator<E, T> newInstance(String className)

I want to ensure that the class found for this name is a valid subclass of Evaluator using isAssignableFrom() :

    Evaluator<E, T> evaluatorInstance = null;
    try {
        Class<?> evaluatorClass = Class.forName(className);
        if (!Evaluator.class.isAssignableFrom(evaluatorClass)) {

        }
        evaluatorInstance = (Evaluator<E, T>) evaluatorClass.newInstance();
    }
    // Catch clause, etc ...

But it gives me a warning about unchecked cast, i was wondering then how to take in account the generic type provided for the class checking (using isAssignableFrom() or any other valid java mecanism).

Hope it was clear :).

PS : If you have other suggestion for the solution design please let me know, i am curious about the best way to modelize such system in Java, without run in ServiceProvider pattern which is too big for the project need.

4

2 回答 2

2

泛型是编译时检查,在运行时没有意义。为只有编译器尊重的东西添加运行时检查是没有意义的。

于 2013-09-20T20:45:56.147 回答
1

此信息在编译时被删除。见 JLS:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.6

于 2013-09-20T20:50:34.803 回答