Description
As a kind of follow-up of the idea I had when creating #905 (cc @cstancu) and of our recent discussions about how to improve GraalVM native static analysis to require less reflection configuration (important for Spring but not only), I think I have found an area where GraalVM native could be improved.
The repro is pretty simple, consider:
interface Foo {
String foo();
}
public class FooImpl implements Foo {
@Override
public String foo() {
return "foo";
}
}
If I try to instantiate FooImpl
via FooImpl.class.getDeclaredConstructor().newInstance()
, the application compiles without reflection configuration needed:
public class App {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Foo foo = FooImpl.class.getDeclaredConstructor().newInstance();
System.out.println(foo.foo());
}
If I just extract the instantiation logic to a method (that's what we do with org.springframework.beans.BeanUtils#instantiateClass(java.lang.Class<T>)
that is used everywhere in Spring) like that:
public class App {
public static void main(String[] args) {
Foo foo = instantiateClass(FooImpl.class);
System.out.println(foo.foo());
}
public static <T> T instantiateClass(Class<T> clazz) {
try {
return clazz.getDeclaredConstructor().newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Then running the native image fails with java.lang.NoSuchMethodException: com.sample.FooImpl.<init>()
and requires reflection to work as expected. Same behavior if I use org.springframework.beans.BeanUtils#instantiateClass(java.lang.Class<T>)
.
Could you improve GraalVM native in order to support this kind of use case without requiring reflection configuration? I think that could allow us to support most function Spring application with almost no reflection configuration and would lead to smaller images that would consume less memory.
Repro project: https://github.com/sdeleuze/graal-issues/tree/master/reflection-static-analysis
Tested with GraalVM 20.1.0
Please tag this issue with spring
label.