睿思看到的一道有趣的秋招笔试题,转帖一下
public class A {
protected String getString() {
return "A";
}
}
public class B extends A {
protected String getString() {
return "B";
}
}
public class C extends B {
}
要求在C中访问A的getString(),
首先想到super.super发现无法编译
然后想到强转,由于多态机制貌似行不通
又尝试下反射,this.getclass().getSuperClass().getSuperClass().getMethod(…).invoke(…);发现权限是protected
写法1
class A {
protected String getString() {
return "A";
}
}
class B extends A {
protected String getString() {
return "B";
}
}
public class C extends B {
public static void main (String args[]){
Class a=C.class.getSuperclass().getSuperclass();
try{
Object o=a.newInstance();
A c=(A)o;
System.out.println(c.getString());
}catch(Exception e){
}
}
}
写法2
class A{
protected String getString() {
return "A";
}
}
class B extends A{
protected String getString() {
return "B";
}
}
public class C extends B{
public static void main(String[] args) {
Class a = C.class.getSuperclass().getSuperclass();
try {
Method m = a.getDeclaredMethod("getString",null);
System.out.println(m.invoke(a.newInstance(),null));
} catch (Exception e) {
e.printStackTrace();
}
}
}