Ser*_*lov 1 java generics reflection
public class A<T> {
public <K> void m(A<K> target) {
// determine if T equals K
}
}
Run Code Online (Sandbox Code Playgroud)
有可能检查是否<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 ) );
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它:
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
Run Code Online (Sandbox Code Playgroud)
该类不必是抽象的,但它可以作为使其成为匿名内部类的提醒.唯一真正的缺点是你必须把它放到{}最后.