views:

51

answers:

2

Hi Folk, Here is a sample java program. I wonder why the two approaches reslut different stories. Is it a bug or kind of bitter java feature?

And I run the sample upon java 1.5

package test;

public class TestOut{

public static void main(String[] args){

**new TestIn();//it works**

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

private static class TestIn{}

}
+3  A: 

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.

Bozho
How come explicit `new` works even if it's `private`, though?
polygenelubricants
I think because reflection eliminates the context, and the context is that the inner class belongs to the outer. The Class object itself retains the reference to the enclosing class, but the Constructor doesn't.
Bozho
3x,Bozho. the "context" is what I am really wondering. IMHO, the Constructor should have enough information to know the enclsong class, and there seems no good reason to implement it in this way.
MikeJiang
@MikeJiang, @polygenelubricants - see my update. The problem is actually elsewhere ;)
Bozho
I was about to file a bug, but there is a bug in the password reset option of sun.com. I reported it, so first they'd have to resolve it, and then I'll be able to file the real bug ;)
Bozho
+1  A: 

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

polygenelubricants
and a very old one :)
Bozho