简体   繁体   中英

Java - Running external code

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM