不多说,先上代码,随后解释
public class GrandPa<T> {<pre name="code" class="java">
private Class<T> myClass;public GrandPa(){if (ParameterizedType.class.isAssignableFrom(super.getClass().getGenericSuperclass().getClass()))
<span style="white-space:pre"> </span>//关键的代码就这一句,<span style="font-family: Arial, Helvetica, sans-serif;">myClass,就获得了子类传进来的实际类了.</span>
this.myClass = ((Class) ((ParameterizedType) super.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
System.out.println("" + myClass.toString());
}
public String toString(){
System.out.println("" + myClass.toString());
return null;
}
}
public class Parent extends GrandPa<AEntity> {
}
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
parent.toString();
}
}
//输出
interface test.AEntity
interface test.AEntity