public class Test {
private static Object createInstance(String classPath) {
try {
Class<?> tClass = Class.forName(classPath);
if (tClass != null) {
return tClass.newInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
public final static <INPUT, OUTPUT> Filter<INPUT, OUTPUT> getFilter(String path) {
return (Filter<INPUT, OUTPUT>) createInstance(path);
}
public final static <INPUT, OUTPUT> OUTPUT filter(String path, INPUT mes) {
Filter<INPUT, OUTPUT> filter = getFilter(path);
//How to check the INPUT and OUTPUT type here?
//if(INPUT instanceof String){ ... } not work
return filter.filter(mes);
}
}
refer to my earlier question here
thanks for help 🙂
Other answer are certainly correct. Anyway i think you are doing something quite unusual.
I’ll try to explain:
Generics are use for static polymorphism. An instance of a generic type is determined at compile time.
Constructs like instanceof are used to check dynamic type of an object at runtime, so if you are using them, you can simply avoid the use of generics.
(You can use a generic Object as parameter for your function and then use instanceof to check its type)
For example:
Typically, if you use generics, you are just trying to avoid that constructs. Typically a generic type can implements a well know interface, in a way that any operation performed upon that object into your filter method, could be performed for different types of objects implementing that interface and without knowing the specific type of objects involved.
I don’t know exactly what are the polymorphic feature that you need, anyway you could try also something like that: