考虑以下:
public class A {
public String name = "i am a A instance";
}
public class B extends A {
public String name = "i am a B instance";
}
public class ReflectTest {
/**
* @param args
*/
public static void main(String[] args) {
A ainstance = new A();
A binstance = new B();
B bbinstance = new B();
System.out.println(bbinstance.name);
System.out.println(ainstance.getClass().cast(binstance).name);
System.out.println(ainstance.getClass().cast(bbinstance).name);
System.out.println(ainstance.getClass().cast(binstance).getClass());
System.out.println(ainstance.getClass().cast(bbinstance).getClass());
}
}
输出是:
i am a B instance
i am a A instance
i am a A instance
class cs236703.s2013.hw4.tests.B
class cs236703.s2013.hw4.tests.B
有没有办法在最后 2 个 printlns 中操纵 Java 反射以返回 A 类而不是 B 类?