反复访问内部类时的异常 [英] Exception when access inner class reflectively

查看:120
本文介绍了反复访问内部类时的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是在Java 1.5中测试的示例程序。

Here is a sample program tested in Java 1.5.

我想知道为什么下面的两种方法有不同的结果。它是一个bug还是一种Java特性?

I wonder why the two approaches below have different result. Is it a bug or a kind of Java feature?

package test;

public class TestOut {
    public static void main(String[] args) {
        // works
        new TestIn();

        // throws IllegalAccessException
        Class.forName("test.TestOut$TestIn").newInstance();
    }

    private static class TestIn {
    }
}


推荐答案

该类是私有的,因此 IllegalAccessException - 您可以使用:

The class is private, hence the IllegalAccessException - you can use:

Class cls = Class.forName(...);
Constructor c = cls.getDeclaredConstructors()[0];
c.setAccessible(true);
c.newInstance();

对于记录,异常有一条消息,这是一个非常具有描述性的消息。下次不要从问题中省略这些信息。 (实际上,我不确定Java 1.5上是否存在此消息,是吗?)

For the record, the exception has a message, which is quite descriptive. Next time don't omit such information from the question. (actually, I'm not sure this message exists on Java 1.5, does it?)


类test.Test无法访问成员class test.TestOut $ TestIn with modifiersprivate

Class test.Test can not access a member of class test.TestOut$TestIn with modifiers "private"

问题出在 verifyMemberAccess(.. ) sun.reflect.Reflection 的方法,并且它没有考虑封闭的类。如果成员(构造函数)是私有的,则拒绝访问。

The problem lies in the verifyMemberAccess(..) method of sun.reflect.Reflection, and that it doesn't take into account enclosing classes. If a member (constructor) is private, access is denied.

这篇关于反复访问内部类时的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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