I'm bothered by the question whether the address of anonymous inner class in Java keep invariable.
I made some test codes,
public class AnonymousInnerClass {
public static void main(final String[] args) {
for (int i = 0; i < 5; i++) {
final Runnable x = () -> {
};
System.out.println(x);
}
for (int i = 0; i < 5; i++) {
final int j = i;
final Runnable x = () -> {
final int k = j;
System.out.println(k);
};
System.out.println(x);
}
}
}
and the outputs are not consistent.
main.AnonymousInnerClass$$Lambda$1/0x0000000800000a00@7a46a697
main.AnonymousInnerClass$$Lambda$1/0x0000000800000a00@7a46a697
main.AnonymousInnerClass$$Lambda$1/0x0000000800000a00@7a46a697
main.AnonymousInnerClass$$Lambda$1/0x0000000800000a00@7a46a697
main.AnonymousInnerClass$$Lambda$1/0x0000000800000a00@7a46a697
main.AnonymousInnerClass$$Lambda$2/0x0000000800000c18@532760d8
main.AnonymousInnerClass$$Lambda$2/0x0000000800000c18@57fa26b7
main.AnonymousInnerClass$$Lambda$2/0x0000000800000c18@5f8ed237
main.AnonymousInnerClass$$Lambda$2/0x0000000800000c18@2f410acf
main.AnonymousInnerClass$$Lambda$2/0x0000000800000c18@47089e5f
It seems the address is invariable if class is simple, I'm wondering that's compiler optimizing behavior or language specification.
More realistic scenario, I'm working with Android's MutableLiveData
.
Suppose I have a variable passwd
,
public final MutableLiveData<String> passwd = new MutableLiveData<>("");
and passwd
has a method public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer)
.
Normally I call it with an anonymous inner class passwd.observe(mLifecycleOwner, str -> doSomething());
, and maybe call it several times.
Api doc said the call would be ignored if the observer has been always registered, that's what I need. But this relies on the address of str -> doSomething()
would not change.
I don't want to extract it to a named variable, so I want to know if I can get a language specification guarantee that its address would not change, or if there are some conventions or patterns to handle this situation.