用java反射实例化私有内部类

用java反射实例化私有内部类

本文介绍了用java反射实例化私有内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 Java 反射从另一个类实例化私有内部类.例如,如果我拿了这个代码

Is it possible to instantiate a private inner class from another class using Java reflection. For example if I took this code

public class Main {
    public static void main(String[] args) {}
}

class OtherClass {
    private class Test {}
}

是否可以从类 main 中的 main 方法实例化并访问 Test.

is it possible to instantiate and gain access to Test from the main method in the class main.

推荐答案

当使用反射时,您会发现该内部类的构造函数将外部类的实例作为附加参数(总是第一个).

When using reflection, you'll find constructors of that inner class taking an instance of the outer class as an additional argument (always the first) .

有关相关信息,请参阅这些问题:

See these questions for related information:

如何在 Android 上通过反射实例化成员类

在Java中,不在内部类时如何访问外部类?

示例:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class OuterClass {

    private class InnerClass {

    }

    public OuterClass() {
        super();
    }

    public static void main(String[] args) {
        // instantiate outer class
        OuterClass outer = new OuterClass();

        // List all available constructors.
        // We must use the method getDeclaredConstructors() instead
        // of getConstructors() to get also private constructors.
        for (Constructor<?> ctor : OuterClass.InnerClass.class
                .getDeclaredConstructors()) {
            System.out.println(ctor);
        }

        try {
            // Try to get the constructor with the expected signature.
            Constructor<InnerClass> ctor = OuterClass.InnerClass.class
                    .getDeclaredConstructor(OuterClass.class);
            // This forces the security manager to allow a call
            ctor.setAccessible(true);

            // the call
            try {
                OuterClass.InnerClass inner = ctor.newInstance(outer);
                System.out.println(inner);
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

这篇关于用java反射实例化私有内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:04