访问任何类型的"闭包变量"反过来在匿名类实例中

时间:2013-06-23 00:21:23

标签: java reflection

含糊地说,在Java中,匿名类提供了某种闭包:可以从匿名类中访问(final)变量。在下文中,我将这种变量称为“闭包变量”

The anonymous class's constructor signature differs whether such variables are constant or non-constant

是否有一种优雅的方式来访问非常量“闭包变量”反思

这是我的测试课,它说明了这一挑战:

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无法“烘焙”并且只能在运行时确定。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

newInstance(this, variableString);