Jaquarh
Jaquarh

Reputation: 6693

Executing a jar file method and retrieving return

I am building a platform that allows the use of installing apps. The apps will be a compiled java program (.jar) file which the main platform should be able to read set methods from.

So far, after miles of research I found there was a lot of security flaws in this process but cannot think of any other ways around it.

I am getting this error:

java.lang.ClassNotFoundException: iezon.app.SettingsApp

This is the way I read the app .jar file:

Class<?> app = Class.forName(
    "iezon.app.SettingsApp",
    true,
    new URLClassLoader (new URL[] {
        new URL("file://C://Temp/SettingsApp.jar")
    },
    ClassLoader.getSystemClassLoader())
);

This is the way I invoke the method:

Method method;
    try {
        method = app.getDeclaredMethod("run");
        Object instance = app.newInstance();
        JPanel result = (JPanel) method.invoke(instance);
        Window.frame.getContentPane().add(result);
    } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

The file does exist in the Temp directory and has a package iezon.app with a JPanel class named SettingsApp with code that looks like this:

public SettingsApp() {
    setBounds(0, 0, 584, 462);
    setLayout(null);

    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 450, 300);
    add(panel);
    panel.setLayout(null);

    JLabel lblSettings = new JLabel("SETTINGS APP V2");
    lblSettings.setBounds(107, 11, 249, 29);
    lblSettings.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 19));
    panel.add(lblSettings);

}

public JPanel run(Locale l) {
    return this;
}

Please, any help to this would be so great-full or any pointing in a direction of another way to implement this.

Upvotes: 1

Views: 55

Answers (1)

Gnk
Gnk

Reputation: 720

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class CustomClassLoader {

public static void main(String[] args) {
    try {
        URLClassLoader clsLoader = URLClassLoader.newInstance(new URL[] {new URL("file:/C://ambienteDesenv/bitbucket/testJar.jar")});
        Class cls = clsLoader.loadClass("testeJar.TestClass");

        Method m = cls.getMethod("getValue");
        Object a = m.invoke(cls.newInstance());
        System.out.println(a);


    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | MalformedURLException | InstantiationException e) {
        e.printStackTrace();
    }
}
}

Upvotes: 3

Related Questions