能否为同一个Java匿名类创建多个新对象?
Great question! Let's start by breaking down a core detail about anonymous classes: they don’t have a user-defined name—the compiler generates a hidden name like OuterClass$1 for them, but we can’t reference this name directly in our code. That means we can’t just write new OuterClass$1() to make another instance. However, there are two reliable ways to create multiple instances of the same anonymous class:
1. Use a factory method
Wrap the creation logic of your anonymous class inside a method. Every time you call this method, it returns a new instance of the same anonymous class (the compiler only generates one class definition for this method’s anonymous inner class).
Here’s a concrete example:
abstract class Employee { abstract void get(); void set() {} } public class AnonymousClassDemo { public static void main(String[] args) { // Create two instances of the same anonymous class Employee emp1 = createCustomEmployee(); Employee emp2 = createCustomEmployee(); // Verify they belong to the same class System.out.println(emp1.getClass() == emp2.getClass()); // Outputs true emp1.get(); // Calls the anonymous class's get() method emp2.get(); } // Factory method that returns instances of the same anonymous class private static Employee createCustomEmployee() { return new Employee() { @Override void get() { System.out.println("Executing get() from the anonymous class"); } void put() { System.out.println("Executing put() from the anonymous class"); } }; } }
2. Use reflection with the anonymous class's Class object
If you already have one instance of the anonymous class, you can get its Class object and use reflection to create new instances. This is less straightforward than the factory method, but it works when you can’t predefine a factory.
Example:
abstract class Employee { abstract void get(); void set() {} } public class AnonymousClassReflectionDemo { public static void main(String[] args) throws Exception { // Create the first instance of the anonymous class Employee emp1 = new Employee() { @Override void get() { System.out.println("Anonymous class get() called"); } void put() {} }; // Get the Class object of the anonymous class Class<? extends Employee> anonClass = emp1.getClass(); // Use reflection to create a new instance (handle access restrictions if needed) var constructor = anonClass.getDeclaredConstructor(); constructor.setAccessible(true); // Bypass access checks if the constructor is non-public Employee emp2 = constructor.newInstance(); // Confirm they're the same class System.out.println(emp1.getClass() == emp2.getClass()); // Outputs true emp2.get(); } }
Key takeaway
While you can’t directly instantiate an anonymous class by name, you can reuse its definition via factory methods or reflection to create multiple instances. The factory method approach is the cleaner, more maintainable option for most use cases.
内容的提问来源于stack exchange,提问作者Ishwar

