在我的当前项目中,我有像以下模型的类。在某个时刻,会在类A和类B上调用
getReturnTypeForGetId()
这样的方法。使用类A调用该方法返回预期的Integer
,但使用类B则返回Serializable
。我漏掉了什么吗?是受到一些可怕的擦除影响,还是我忽略了某种泛型上下文覆盖?编辑:向类B添加一个重载的getId()
方法可以解决问题,但我仍然想理解我遇到了什么问题。import java.io.Serializable;
public class WeirdTester {
static interface Identifiable<T extends Serializable> {
T getId();
void setId(final T id);
}
static abstract class BaseEntity<T extends Serializable> implements Identifiable<T> {
private T id;
public T getId() { return id; }
public void setId(final T id) { this.id = id; }
}
static class A implements Identifiable<Integer> {
private Integer id;
public Integer getId() { return id; }
public void setId(final Integer id) { this.id = id; }
}
static class B extends BaseEntity<Integer> {}
@SuppressWarnings("unchecked")
private static <T extends Serializable, Q extends Identifiable<T>> Class<T> getReturnTypeForGetId(
final Class<Q> clazz) throws Exception {
return (Class<T>) clazz.getMethod("getId", (Class[])null).getReturnType();
}
public static void main(final String[] args) throws Exception {
System.out.println(getReturnTypeForGetId(A.class));
// CONSOLE: "class java.lang.Integer"
System.out.println(getReturnTypeForGetId(B.class));
// CONSOLE: "interface java.io.Serializable"
}
}