2

模糊地说,在 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

但是测试用例打印出以下内容:testInstantiateNonConstantAnonymousClassReflectively

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)

请注意,对于 test case ,会生成不同类型的构造函数。这个构造函数需要一个额外的参数,因为不能“烘焙”并且只能在运行时确定。testInstantiateNonConstantAnonymousClassReflectivelyStringvariableString

4

2 回答 2

1

我不认为你所要求的是可能的。如果变量没有被烘焙到匿名类中,那么它们就不会被烘焙进去。使用反射,它由调用者提供所有构造函数参数,包括合成参数。

这与需要外部实例的内部类的构造函数的动态调用相同。我注意到instantiateAnonymousClass依赖于指定匿名类在同一个类中声明的事实 - 这允许它简单地传入this。它将如何处理在其他地方声明的匿名类?您提到这是一种库方法,因此这是一个需要考虑的重要问题。您的方法可以查找它们的外部类并实例化它们,但是如果它们的构造函数需要更多参数怎么办?最终,它由调用者提供动态调用所需的任何内容。

于 2013-06-23T01:25:33.430 回答
0
newInstance(this, variableString);
于 2013-06-23T00:40:59.690 回答