To better assess the risk of reflection when porting to Java 9, I wonder if fine reflection is safe instead of static compiling while it references an available type:
I mean, can I always replace
PublicType p = (PublicType)(Factory.instance()); p.publicMethod();
(Where Factory.instance() has a return type of Object and will return a subtype of type API ( Package.PublicType ) from a module that is not open).
with
Object p = Factory.instance(); Class<?> c = Class.forName("package.PublicType"); Method m = c.getMethod("publicMethod", (Class[])null); // assert p instanceof package.PublicType m.invoke(p, (Object[])null); // throws?
Earlier versions of this question, where about the problem with the specific code , which I resolved in the meantime.
But the general question is also interesting for discussion: are there cases when the returned object has the correct subtype but does not perform access checks when called or MethodHandle.
source share