lundi 29 août 2022

IllegalAccessException on calling constructor after loading class via URLClassLoader

I try to load a class from file system(which is not in the cp of my main) and then want a new instance of that loaded class like this:

try {
    File folder = new File("/tmp/");
    URLClassLoader loader = URLClassLoader.newInstance(new URL[] {folder.toURI().toURL()});
    Class clazz = loader.loadClass("testpkg.test");
    Constructor constructor = clazz.getConstructor();
    Object instance = constructor.newInstance();
} catch (Exception e) {
    e.printStackTrace();
}

the class file exists in the /tmp/testpkg directory and has the name test.class. The code for the uncompiled .java looks like this:

package testpkg;
class test{
    public test(){
            System.out.println("I am the constructor!");
    }
}

unfortunately I get a runtimeError at the following line:

Object instance = constructor.newInstance();

which says:

java.lang.IllegalAccessException: Class tmp.ClassLoadingFun can not access a member of class testpkg.test with modifiers "public"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
at java.lang.reflect.Constructor.newInstance(Constructor.java:413)
at tmp.ClassLoadingFun.<init>(ClassLoadingFun.java:16)
at tmp.ClassLoadingFun.main(ClassLoadingFun.java:23)

When i fuzz around with the package or class name, it will terminate earlier stating, there is no proper class found. So I guess the loading of the class works. Only calling the constructor does not. Why can't I access this public(!) constructor?





Aucun commentaire:

Enregistrer un commentaire