Java - Running external code

2019-07-27 16:54发布

I want to have a Java program that can read a .CLASS file and run that code, using itself as the .CLASS file's library. Is this at all possible?

1条回答
Emotional °昔
2楼-- · 2019-07-27 17:23

java.lang.ClassLoader

will help you to load external classes.

java.lang.reflect.Method

will help you to invoke methods of loaded external classes.

Tiny example:

ArrayList<URL> urls = new ArrayList<URL>();
urls.add(new File("/path/to/your.class").toURI().toURL()); //can add several..

ClassLoader cl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
Class<?> c;
c = Class.forName("your.class.name", false, cl); //now you have your class

Method m = c.getMethod("main", String[].class); //now your have your method
m.invoke(null, new Object[] { "argument1", "argument2" }); //now you "run that code"

I did not run anything, i just wrote it to show you some tools that can help you.

查看更多
登录 后发表回答