Exception when access inner class reflectively

老子叫甜甜 提交于 2020-01-03 03:33:42

问题


Here is a sample program tested in Java 1.5.

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 {
    }
}

回答1:


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

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

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?)

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

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.




回答2:


This is Bug ID 4221909:

Synopsys: (reflect) Class.newInstance() throws IllegalAccessErrorException when the class has an inner non-public class
State: 6-Fix Understood, bug
Priority: 4-Low
Submit Date: 19-MAR-1999



来源:https://stackoverflow.com/questions/2910168/exception-when-access-inner-class-reflectively

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!