Using java.awt.Toolkit.getDefaultToolkit().getScreenSize() reflectively causes InaccessibleObjectException

Jochen Theodorou blackdrag at
Thu Jan 5 22:09:35 UTC 2017

On 05.01.2017 21:07, Phil Race wrote:
> Sort of .. it depends whether you could use getDeclaredMethod instead.
> One question I have is, how would you update the code if you
> were given the instance "foo", and need to programmatically
> work out what is the correct super-type of Foo that exports
> the interface method "bar" ?
> i.e you don't have the string "java.awt.Toolkit" handy and
> need to infer it from the instance class.

staying in old java style I guess something like this:

Method getMethod(Class c, String name, Class... types) {
   if (c==null) return null
   try {
     return c.getMethod(name, types)
   } catch (Exception e) {
     // ignoring exceptions is fun!
   for (Class ci : c.getInterfaces()) {
     Method ret = getMethod(ci, name, types)
     if (ret!=null) return ret
   return getMethod(c.getSuperClass(), name, types)

If the this getMethod returns a method then you should have something 
you can invoke on. Just searching the super classes is not enough, the 
only exported type might be an interfaces, so you have to go through 
those too. I leave the version with lambdas, flat-mapped streams, 
Optionals and useless generics/semicolons to somebody else ;)

I think a version using MethodHandles would be similar, since I think 
the game is the same if you use Lookup#findVirtual instead of 
Class#getMethod... only that in the end you could of course just return 
a MethodHandle that throws one (of the countless) exceptions this code 
may have produced...

I'd love to see a better solution though..

bye Jochen

More information about the jigsaw-dev mailing list