如果我有一个内部类的实例,我如何从不在内部类中的代码访问外部类?我知道在内部类中,我可以Outer.this用来获取外部类,但我找不到任何外部方法来获取它.
例如:
public class Outer {
public static void foo(Inner inner) {
//Question: How could I write the following line without
// having to create the getOuter() method?
System.out.println("The outer class is: " + inner.getOuter());
}
public class Inner {
public Outer getOuter() { return Outer.this; }
}
}
Run Code Online (Sandbox Code Playgroud) 我知道 Java 编译器会根据上下文和闭包为 lambda 函数生成不同的类。当我接收 lambda 作为参数(使用Consumer<>类)时,我可以知道参数的生命周期吗?
例如,我有以下Observable类,它保持对其观察的弱引用。
class Observable {
private final List<WeakReference<Consumer<Object>>> observables = new ArrayList<>();
private Object obj;
public Observable(Object obj){
this.obj = obj;
}
public void observe(Consumer<Object> cons){
this.observables.add(new WeakReference<>(cons));
}
public void set(Object obj){
this.obj = obj;
// notify observes
for(WeakReference<Consumer<Object>> cons : this.observables){
if(cons.get() != null)
cons.get().accept(this.obj);
// clearing the non-existing observes from the list is ommited for simplicity
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我使用它如下。
public class Main {
public static void …Run Code Online (Sandbox Code Playgroud)