Anonymous-Inner classes showing incorrect modifier

Note that the wording in the JLS of that particular section has changed significantly since then. It now (JLS 11) reads: 15.9.5. Anonymous Class Declarations: An anonymous class is never final (ยง8.1.1.2). The fact that an anonymous class is not final is relevant in casting, in particular the narrowing reference conversion allowed for the cast … Read more

NotSerializableException on anonymous class

Joshua Bloch writes in his book Effective Java, 2nd Edition, Item 74: Inner classes should not implement Serializable. They use compiler-generated synthetic fields to store references to enclosing instances and to store values of local variables from enclosing scopes. How these fields correspond to the class definition is unspecified, as are the names of anonymous … Read more

Do anonymous classes *always* maintain a reference to their enclosing instance?

As of JDK 18, no. JDK 18 omits enclosing instance fields from inner classes that don’t use it. However, prior to JDK 18, yes, instances of anonymous inner classes hold on to a reference to their enclosing instances even if these references are never actually used. For example, this code: public class Outer { public … Read more

Why is an anonymous inner class containing nothing generated from this code?

I’m using polygenelubricants’s smaller snippet. Remember there’s no concept of nested classes in the bytecode; the bytecode is, however, aware of access modifiers. The problem the compiler is trying to circumvent here is that the method instantiate() needs to create a new instance of PrivateInnerClass. However, OuterClass does not have access to PrivateInnerClass‘s constructor (OuterClass$PrivateInnerClass … Read more

How to pass parameters to anonymous class?

Yes, by adding an initializer method that returns ‘this’, and immediately calling that method: int myVariable = 1; myButton.addActionListener(new ActionListener() { private int anonVar; public void actionPerformed(ActionEvent e) { // How would one access myVariable here? // It’s now here: System.out.println(“Initialized with value: ” + anonVar); } private ActionListener init(int var){ anonVar = var; return … Read more

tech