Frederik Olsen
Frederik Olsen

Reputation: 58

How to call a method from a class in another .jar?

I have .jar-file, called Plugin.jar which contains a single class, plugin.Plugin, with the method public ArrayList<String> getList().

I am trying to call that method from my main program, which is a completely different NetBeans project.

However, I get a java.lang.IllegalArgumentException: object is not an instance of declaring class on the last line before the catch clause.

The main program (the one that is calling getList() in the other .jar) looks like this:

public class PluginMain {

    public static void main(String[] args) {
        try {
            File file = new File("plugins/Plugin.jar");
            URL url = file.toURI().toURL();
            URL[] urls = new URL[]{url};
            ClassLoader cl = new URLClassLoader(urls);

            Class cls = cl.loadClass("plugin.Plugin");
            Method method = cls.getDeclaredMethod("getList");
            ArrayList<String> invoke = (ArrayList<String>) method.invoke(cls);
        } catch (MalformedURLException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(PluginMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

The plugin.Plugin class from the Plugin.jar looks like this:

public class Plugin {

    public Plugin() {
    }

    public ArrayList<String> getList(){
        ArrayList<String> list = new ArrayList();
        list.add("String1");
        list.add("String2");
        list.add("String3");
        return list;
    }
}

This is my first time attempting anything like this and I'm truly lost, as to what I should do to fix the exception. Any help will be appreciated.

Upvotes: 1

Views: 4285

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280179

The Method#invoke(Object, Object...) method expects an instance of the class to which the method belongs.

You have a few choices with reflection. If your class has a no-args constructor (as it does), you can use

Object instance = cls.newInstance();

and then pass that

ArrayList<String> invoke = (ArrayList<String>) method.invoke(instance);

If your class doesn't have a no-args constructor, you'll need to choose from the available constructors with

Constructor[] constructors = cls.getConstructors();

I am trying to call that method from my main program, which is a completely different NetBeans project.

Note that as long as the class files are on the class path, you can very much just do

Plugin plugin = new Plugin();
...

the fact that it's in a different project has nothing to do with how you run a java program.

Upvotes: 3

Related Questions