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

Alan Bateman Alan.Bateman at oracle.com
Wed Jan 24 19:48:31 UTC 2018


On 24/01/2018 15:42, Rony G. Flatscher wrote:
>
> OK, now add to this the following class that uses p.C2 objects to 
> access e.g. m() via it:
>
>     G:\xfer\java9modules\03-20180124-AlanBatmanP\p>type UseC2.java
>
>     public class UseC2
>     {
>         public static void main (String args[]) {
>             p.C2 o=new p.C2();
>             System.out.println("o="+o);
>             System.out.println("o.m()="+o.m());
>         }
>     }
>
> Compiling all three classes works.
>
> Running "UseC2" works and outputs:
>
>     G:\xfer\java9modules\03-20180124-AlanBatmanP\p>java -cp ".;.." UseC2
>     o=p.C2 at 66048bfd
>     o.m()=-1
>
> So it is possible to access m() via the p.C2 object from UseC2.
That's right and this is the reason for moving to the simpler example.

To be absolutely sure then you should decompile C2.class to make sure 
that there isn't a bridge method calling C1's m2(). If you change m() to 
be final then that will keep the bridge method from complicating the 
picture.

If you change UseC2 to use core reflection and you hit the issue because 
the Method object you get is p.C1.m(). Attempting to invoke this will 
fail with IllegalAccessException. In your other mail you show a code 
fragment where it catches exceptions and calls setAccessible - I'll 
guess that this may have been masking the issue in the Rexx bridge.

For completeness then you may want to try out the new reflection API. I 
realize you have to compile to JDK 6 but I think you'll find it will 
work the same way as the invokevirtual that o.m() compiles to.

     MethodHandles.Lookup lookup = MethodHandles.lookup();
     MethodType mt = MethodType.methodType(int.class);
     MethodHandle mh = lookup.findVirtual(p.C2.class, "m", mt);
     Object res = mh.invoke(o);

-Alan







More information about the jigsaw-dev mailing list