interface A {
void show();
}
public class Static {
public static void main(String args[]) {
A a = new A(){
public void show(){
System.out.println("In anonymous Class");
A b =new A(){
public void show(){
System.out.println("In nested Anonymous Class");
}
};
}
};
//a.show();
}
}
如果我想打印“In nested Anonymous Class”,我应该使用什么来代替 a.show()?
//稍后编辑
谢谢大家,但不幸的是,我打错了代码……我不是说方法内部的匿名类……而是在类本身内部。抱歉弄错了。这是更正后的代码
interface A {
void show();
}
public class Static {
public static void main(String args[]) {
A a = new A() {
public void show() {
System.out.println("In anonymous Class");
};
A b = new A() {
public void show() {
System.out.println("In nested Anonymous Class");
}
};
};
a.show();
}
}
最佳答案
通常情况下,这是不可能的,因为 A 是一个接口(interface),而接口(interface)没有字段。但是,可以使用反射访问该字段。虽然有点 hack,但我不建议在“现实世界”中使用它!
interface A {
void show();
}
public class Static {
public static void main(String args[]) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
A a = new A() {
public void show() {
System.out.println("In anonymous Class");
};
public A b = new A() {
public void show() {
System.out.println("In nested Anonymous Class");
}
};
};
// Get the anonymous Class object
Class<? extends A> anonymousClass = a.getClass();
// Get field "b"
Field fieldB = anonymousClass.getField("b");
// Get the value of b in instance a and cast it to A
A b = (A) fieldB.get(a);
// Show!
b.show();
}
}
注意:更好的方法可能是简单地在您的接口(interface)上为变量 b 声明一个 getter。
关于java - 有没有办法访问另一个匿名类中的匿名类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25823293/