public class A<T> {
public <K> void m(A<K> target) {
// determine if T equals K
}
}
是否可以检查 <T>
和 <K>
是同一种类型吗?
最佳答案
是的,这与通用 TypeReference 的工作方式相同.通常类型被删除,但它适用于匿名内部类:
public abstract class A<T> {
private Type type;
public A() {
Type superclass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
public <K> void m(A<K> target) {
System.out.println( type.equals( target.type ) );
}
}
使用方法:
A<String> as = new A<String>(){};
A<String> a2s = new A<String>(){};
A<Integer> ai = new A<Integer>(){};
as.m(a2s); // prints true
as.m(ai); // prints false
该类不必是抽象的,但它可以提醒您使其成为匿名内部类。唯一真正的缺点是您必须将 {}
放在最后。
关于java - 确定泛型类型是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9931611/