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);
}
}
引用我之前的问题here
感谢您的帮助:)
最佳答案
其他答案肯定是正确的。无论如何,我认为你正在做一些非常不寻常的事情。 我将尝试解释:
泛型用于静态多态性。泛型类型的实例是在编译时确定的。
像 instanceof 这样的构造用于在运行时检查对象的动态类型,因此如果您使用它们,您可以简单地避免使用泛型。 (您可以使用通用对象作为函数的参数,然后使用 instanceof 检查其类型) 例如:
public void method(Object o){
if (o instanceof String){} //do what you want
else ....
}
通常,如果您使用泛型,您只是在尝试避免这种构造。通常,泛型类型可以实现众所周知的接口(interface),在某种程度上,在该对象上执行的任何操作进入您的过滤器方法,都可以针对实现该接口(interface)的不同类型的对象执行,而无需知道所涉及的对象的特定类型。
我不知道你到底需要什么多态特性,无论如何你也可以尝试类似的东西:
public interface polymorphicObj{
public method();
}
public class Filter<GENERIC implements polymorphicObj>{
public filter(GENERIC obj){
obj.method(); //you don't need to know of which specific type is polymorphicObj
}
}
关于java - 如何检查java模板方法中的类类型(instanceof)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5367890/