Generics are a compile time check and are not meaningful at runtime. It doesn't make sense to add a runtime check for something only the compiler honours.
Using isAssignableFrom() with generic interface
-
29-06-2022 - |
Domanda
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.
Soluzione
Altri suggerimenti
This information is erased at compile time. See the JLS:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.6