Reflection: how does one access a protected member in a superclass reflectively?
Rony G. Flatscher
Rony.Flatscher at wu.ac.at
Thu Jan 18 15:11:15 UTC 2018
On 18.01.2018 10:58, Alan Bateman wrote:
> On 17/01/2018 18:53, Rony G. Flatscher wrote:
>>
>> :
>>
>> Would you have concrete suggestions for this use-case, i.e. a framework that is not part of a
>> module, but having a need to access public types from exported packages and get reflective access
>> to objects supertype's protected members?
> I think it would be better to start with public members as protected is complicated (and hasn't
> changed with modules once you establish the class declaring the member is accessible).
>
> For your example, you've got a reference to a java.awt.Graphics2D object, the actual
> implementation type is sun.java2d.SunGraphics2D. The user is attempting to invoke one of the
> public setRenderingHint methods that Graphics2D defines. You said in one of your mails that the
> bridge "iterates over all its superclasses" which I take to mean that it recursively looks at the
> superclass and interfaces to find a public class or interface that defines the target
> setRenderingHint method. In the example, I expect it would skip sun.java2d.SunGraphics2D if it
> were non public.
>
> Can you extend this check to test if the class is in a package exported by its module. For the
> example, sun.java2d.SunGraphics2D is in the java.desktop module and this module does not export
> sun.java2d to everyone. Here is a code fragment to test this:
>
> Class<?> clazz = graphicsObj.getClass();
> boolean isExportedToAll = clazz.getModule().isExported(clazz.getPackageName());
>
> (I'm deliberately avoiding the 2-arg isExported to keep things simple for this discussion).
>
> If you can incorporate this check into the bridge then I suspect you'll find most of the examples
> will work.
Yes, I understand (not being able to use methods in an unexported type's instance, hence the need to
find an accessible member in a superclass, which means to have a need to also access protected
members in the superclass) and that is actually my current approach. However, I started out with
reflecting Fields first and see, whether I can reflectively get access.
The rewritten method resolution would follow next, which would allow me to tackle that warning and
see whether I can get rid of it. However, before going a wrong route I would like to learn what the
"official" Java 9 solution would be and try to implement that.
---rony
More information about the jigsaw-dev
mailing list