使用java反射实例化私有内部类 [英] Instantiate private inner class with java reflection

查看:317
本文介绍了使用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) .

这些问题的相关信息:

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

In Java, how do I access the outer class when I'm not in the inner class?

b

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反射实例化私有内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆