从Java中的内部类访问外部类“super”
如何从内部类访问外部类’ super
?
我重写了一个让它在不同的线程上运行的方法。 从内联线程,我需要调用原始方法,但当然只是调用method()
将变成无限递归。
具体来说,我正在扩展BufferedReader:
public WaitingBufferedReader(InputStreamReader in, long waitingTime) { [..] @Override public String readLine() { Thread t= new Thread(){ public void run() { try { setMessage(WaitingBufferedReader.super.readLine()); } catch (IOException ex) { } } }; t.start(); [..] } }
这个地方给了我一个我无法找到的NullPointerException。
谢谢。
喜欢这个:
class Outer { class Inner { void myMethod() { // This will print "Blah", from the Outer class' toString() method System.out.println(Outer.this.toString()); // This will call Object.toString() on the Outer class' instance // That's probably what you need System.out.println(Outer.super.toString()); } } @Override public String toString() { return "Blah"; } public static void main(String[] args) { new Outer().new Inner().myMethod(); } }
上述测试在执行时显示:
Blah Outer@1e5e2c3