JDK-8193172 : Refection vs Compiler gives different access levels to package-private classes
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 8u152
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_10
  • CPU: x86_64
  • Submitted: 2017-12-06
  • Updated: 2018-01-02
  • Resolved: 2017-12-07
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
Java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows [Version 10.0.10586]

A DESCRIPTION OF THE PROBLEM :
If you create a package-private class with one public final method and extend it with another class that is package public.   The method is assessable via compiled java code but not via reflections. 

Exception in thread "main" java.lang.IllegalAccessException: Class experiment.b.C can not access a member of class experiment.a.A with modifiers "public final"
	at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
	at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
	at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
	at java.lang.reflect.Method.invoke(Method.java:491)
	at experiment.b.C.main(C.java:13)



EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Consistency. Each approach should have the same access level
ACTUAL -
. Each approach has different access level

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Exception in thread "main" java.lang.IllegalAccessException: Class experiment.b.C can not access a member of class experiment.a.A with modifiers "public final"
	at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
	at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
	at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
	at java.lang.reflect.Method.invoke(Method.java:491)
	at experiment.b.C.main(C.java:13)


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
package experiment.a;
class A {
	private String a;

	public final String getA() {
		return a;
	}

	public final void setA(String a) {
		this.a = a;
	}
}


package experiment.a;
public class B extends A {
   
}

package experiment.b;
import experiment.a.B;
public class C {
  public static void main(String[] args) throws Exception {
	  B b = new B();
	  b.setA("hi");
	  
	  b.getClass().getMethods()[0].invoke(b, "bye");
  }
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Use adapter pattern to wrap the object  so that third party tool can introspect.