遵循超类/子类关系:
public abstract class A {
public Class<? extends A> getSubClass() {
Class<? extends A> clazz = ???
}
}
public class B extends A {
/* some implementation*/
}
public class Foo {
public static void main(String... args) {
A a = new B();
a.getSubClass();
}
}
b.getSubClass()
是否有办法返回acutall子类类型?
答案 0 :(得分:0)
此
package test;
public class SubClass {
public static void main(String[] args) {
final A b = new B();
System.out.println("Class: " + b.getSubClass().getName());
}
public static abstract class A {
public Class<? extends A> getSubClass() {
return this.getClass();
}
}
public static class B extends A {
// No further implementation
}
}
产生
Class: test.SubClass$B
即使在超类方法中,实际的类也是子类。