Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Invoking a method causes IllegalAccessError

Tags:

java

I have a simple function for loading the class "Myclass" from the selected directory.

    // Variables
    File temp = new File("some path...");
    String class_name = "MyClass";

    // Directory url
    URL[] urls = null;
    try {
        urls = new URL[]{temp.toURI().toURL()};
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    // Loading the class
    ClassLoader cl = new URLClassLoader(urls);
    Class clazz = null;
    Object clazz_instance = null;
    try {
        // Loads class
        clazz = cl.loadClass(class_name);
        // Creates instance
        clazz_instance = clazz.newInstance();

        // Invoking method "myMethod"
        try {
            Method m = clazz.getMethod("myMethod");
            m.invoke(clazz_instance);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | NullPointerException e) {
            e.printStackTrace();
        }

    } catch (NoClassDefFoundError | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }

Let us assume I have the following class:

public class MyClass {
    public void myMethod() {
        MyOtherClass moc = new MyOtherClass();
        // ...... some code
    }
}

class MyOtherClass {}

But when I want to call the method "myMethod" I get the:

java.lang.reflect.InvocationTargetException
Caused by: java.lang.IllegalAccessError: tried to access class "MyOtherClass" from class "MyClass"

I am asuming that the problems comes from the fact that the "MyOtherClass" is not public (It can not be, since it is in the same file than "MyClass").

How can I fix this ?

like image 211
N10 Avatar asked Mar 17 '16 14:03

N10


1 Answers

This is because you are not loading the dependency class first from the code. Put your MyOtherClass in its own file and set it as public. Then Load it as below.

 cl.loadClass("MyOtherClass");
 cl.loadClass(class_name);

If you stick to have both the classes in the same file. Define it as below

public class MyClass {
    class MyOtherClass {}
    public void myMethod() {
        MyOtherClass moc = new MyOtherClass();

    }
}
like image 188
Thanga Avatar answered Sep 30 '22 19:09

Thanga