United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
Bug ID: JDK-4283544 (reflect) Field and Method do not correctly obey language accessibility rules
JDK-4283544 : (reflect) Field and Method do not correctly obey language accessibility rules

Details
Type:
Bug
Submit Date:
1999-10-21
Status:
Open
Updated Date:
2012-09-28
Project Name:
JDK
Resolved Date:
Component:
core-libs
OS:
solaris_2.5,generic,windows_xp
Sub-Component:
java.lang:reflect
CPU:
x86,sparc,generic
Priority:
P4
Resolution:
Unresolved
Affected Versions:
1.1,1.2.2,5.0
Targeted Versions:

Related Reports
Duplicate:
Relates:

Sub Tasks

Description
java.lang.reflect.Field (get* and set*) and Method (invoke) base their access check on the declaring class.  This is contrary to the JLS, which defines accessibility in terms of the reference type.  Consider the following:

package foo;

class X {
    public int i;
}

package foo;

public class Y extends X {
    public static Object get() { return new Z(); }
}

package foo;

class Z extends Y {}

package bar;

import foo.Y;

public class T {
    public static void main(String[] args) {
	Y y = new Y();
	int i = y.i;
	try {
	    y.getClass().getField("i").getInt(y);
	} catch (Exception e) {
	    e.printStackTrace();
	}
	Object z = Y.get();
	i = ((Y)z).i;
	try {
	    z.getClass().getField("i").getInt(z);
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}

Both of the getInt calls throw IllegalAccessException, contrary to what the compiler allows.

At runtime you need to check if there exists some class, between the declaring class and the actual class (inclusive), that is public.  This could be a bit messy for interface methods, since there isn't a single linear chain to search.

                                    

Comments
EVALUATION

$ 141; java bar.T
java.lang.IllegalAccessException: Class bar.T can not access a member of class foo.X with modifiers "public"
        at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:57)
        at java.lang.reflect.Field.doSecurityCheck(Field.java:811)
        at java.lang.reflect.Field.getFieldAccessor(Field.java:758)
        at java.lang.reflect.Field.getInt(Field.java:369)
        at bar.T.main(T.java:10)
java.lang.IllegalAccessException: Class bar.T can not access a member of class foo.X with modifiers "public"
        at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:57)
        at java.lang.reflect.Field.doSecurityCheck(Field.java:811)
        at java.lang.reflect.Field.getFieldAccessor(Field.java:758)
        at java.lang.reflect.Field.getInt(Field.java:369)
        at bar.T.main(T.java:17)

This is the method/field version of 4071957.  This problem is best solved
via the updated classfile format which is being considered for Tiger.

-- iag@sfbay 2002-05-16
                                     
2002-05-16



Hardware and Software, Engineered to Work Together