我想检查泛型类的实例化类型是否具有某些属性,例如:
class Foo<T> {
void bar () {
if (T instanceof Serializable) // does not compile
...
}
}
我想知道通用信息是否在运行时完全丢失?这是否意味着没有办法完成我想做的事情?
最佳答案
And does that mean there is no way to accomplish what I would like to do?
你可以写:
class Foo<T> {
private final Class<T> clazz;
Foo (final Class<T> clazz) { // require creator to supply a Class<T>
this.clazz = clazz;
if (clazz == null) {
throw new NullPointerException();
}
}
void bar () {
if (Serializable.class.isAssignableFrom(clazz)) {
...
}
}
}
关于java - 在java中获取实例化类型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15045430/