含糊地说,在Java中,匿名类提供了某种闭包:可以从匿名类内部访问(final
)变量。在下文中,我将这类变量称为"闭包变量"。
无论这些变量是常量还是非常量,匿名类的构造函数签名都不同。
是否有一种优雅的方法反射式地访问非常量"闭包变量"?
以下是我的测试类,说明了这一挑战:
package com.example;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
public class ReflectiveInstantiationAnonymousClassTest {
@Test
public void testInstantiateConstantAnonymousClassReflectively() {
System.out
.println("About to define anonymous class with constant closure");
final String constantString = "constant String";
System.out.println("constantString is " + constantString);
Class<? extends Object> clazz = new Object() {
public String toString() {
return "Hello with " + constantString;
}
}.getClass();
Object anonymousClassInstance1 = instantiateAnonymousClass(clazz);
Object anonymousClassInstance2 = instantiateAnonymousClass(clazz);
System.out.println(anonymousClassInstance1);
System.out.println(anonymousClassInstance2);
}
@Test
public void testInstantiateNonConstantAnonymousClassReflectively() {
System.out
.println("About to define anonymous class with variable closure");
final String variableString = String.valueOf( System.currentTimeMillis() );
System.out.println("variableString is " + variableString);
Class<? extends Object> clazz = new Object() {
public String toString() {
return "Hello with " + variableString;
}
}.getClass();
Object anonymousClassInstance1 = instantiateAnonymousClass(clazz);
Object anonymousClassInstance2 = instantiateAnonymousClass(clazz);
System.out.println(anonymousClassInstance1);
System.out.println(anonymousClassInstance2);
}
@SuppressWarnings("unchecked")
private <T> T instantiateAnonymousClass(Class<T> clazz) {
T instance = null;
Constructor<?>[] allConstructors = clazz.getDeclaredConstructors();
System.out.println("-+-" + allConstructors.length + " constructor(s) defined by class " + clazz.getName() );
for(Constructor<?> constructor : allConstructors) {
System.out.println(" +- a constructor with " + constructor.getParameterTypes().length + " parameter(s): " + constructor.toGenericString() );
}
System.out.println();
System.out.println("Instantiating anonymous class");
try {
instance = (T) clazz.getDeclaredConstructors()[0].newInstance(this);
// .
// /|
// how can I provide a variable closure variable there?--------+
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return instance;
}
}
测试用例testInstantiateConstantAnonymousClassReflectively
运行良好并打印出:
About to define anonymous class with constant closure
constantString is constant String
-+-1 constructor(s) defined by class com.example.ReflectiveInstantiationAnonymousClassTest$1
+- a constructor with 1 parameter(s): com.example.ReflectiveInstantiationAnonymousClassTest$1(com.example.ReflectiveInstantiationAnonymousClassTest)
Instantiating anonymous class
-+-1 constructor(s) defined by class com.example.ReflectiveInstantiationAnonymousClassTest$1
+- a constructor with 1 parameter(s): com.example.ReflectiveInstantiationAnonymousClassTest$1(com.example.ReflectiveInstantiationAnonymousClassTest)
Instantiating anonymous class
Hello with constant String
Hello with constant String
但是测试用例testInstantiate
Non
ConstantAnonymousClassReflectively
打印出以下内容:
About to define anonymous class with variable closure
variableString is 1371946280882
-+-1 constructor(s) defined by class com.example.ReflectiveInstantiationAnonymousClassTest$2
+- a constructor with 2 parameter(s): com.example.ReflectiveInstantiationAnonymousClassTest$2(com.example.ReflectiveInstantiationAnonymousClassTest,java.lang.String)
Instantiating anonymous class
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.example.ReflectiveInstantiationAnonymousClassTest.instantiateAnonymousClass(ReflectiveInstantiationAnonymousClassTest.java:60)
at com.example.ReflectiveInstantiationAnonymousClassTest.testInstantiateNonConstantAnonymousClassReflectively(ReflectiveInstantiationAnonymousClassTest.java:43)
请注意,对于测试用例testInstantiate
Non
ConstantAnonymousClassReflectively
,将生成不同类型的构造函数。此构造函数需要一个额外的String
参数,因为variableString
不能"烘焙",只能在运行时确定。
我认为你的要求是不可能的。如果变量没有被烘焙到匿名类中,那么它们就不会被烘焙。使用反射,调用方需要提供所有的构造函数参数,包括合成参数。
动态调用需要外部实例的内部类的构造函数也是如此。我注意到instantiateAnonymousClass
依赖于指定的匿名类在同一个类中声明的事实,这使得它可以简单地传入this
。它将如何处理在其他地方声明的匿名类?你提到这是一种库方法,所以这是一个需要考虑的重要问题。您的方法可以查找它们的外部类并实例化它们,但如果它们的构造函数需要进一步的参数呢?最终由调用者提供动态调用所需的一切。
newInstance(this, variableString);