Reflection: how can one access public fields (members) in a superclass ?

Alan Bateman Alan.Bateman at oracle.com
Wed Jan 24 14:28:14 UTC 2018


On 23/01/2018 14:52, Rony G. Flatscher wrote:
> Given three modules (sources at the end) where
>
>    * "mod_A" exports its package "mtest1", to everyone
>    * "mod_B" requires "mod_A" and exports its package "mtest2" to "mod_C"
>    * "mod_C" requires "mod_B" and exports its package "mtest3" to everyone
>
> "mod_B"'s class "mtest2.Class02A" defines two public fields, one static ("pubStaticFromClass02A")
> and one an instance ("pubFromClass02") one.
>
> Compiling the modules and then using them in the following Java program (via the CLASSPATH) works,
> here the source:
>
>      TestUse_mtest3_Class03A.java
>
>              public class TestUse_mtest3_Class03A
>              {
>                  public static void main (String args[]) {
>                      mtest3.Class03A o=new mtest3.Class03A();
>                      System.out.println("o.pubStaticFromClass02A     : "+o.pubStaticFromClass02A );
>                      System.out.println("o.pubFromClass02A           : "+o.pubFromClass02A     );
>                      System.out.println("o: "+o+", o.getMyClassName(): "+o.getMyClassName());
>                  }
>              }
>
> Compiling the above program and running it yields:
>
>      o.pubStaticFromClass02A     : static-mtest2.Class02A
>      o.pubFromClass02A           : instance-mtest2.Class02A
>      o: mtest3.Class03A at 5afa04c, o.getMyClassName(): via: this=[mtest3.Class03A at 5afa04c],
>      getMyClassName()=[class-mtest1.Class01A]
>
I don't think the questions and observations in this thread are strictly 
modules related. One suggestion is to start with a simpler scenario like 
this:

package p;
class C1 {
     public static final int K = 99;
     public static int k() { return K; }
     public final int F = -1;
     public int m() { return F; }
}

package p;
public class C2 extends C1 { }

No modules or qualified exports in the picture for now. The important 
part is that C1 is not public but it has public members. You can try 
tests to see if references to C2.K, C2.k(), new C2().F, and new C2().m() 
will compile and run. You can try the equivalent with core reflection to 
see how it differs to static references (you may have to change method m 
to be final to prevent javac generating a bridge method in C2).

-Alan.


More information about the jigsaw-dev mailing list