Java - Running external code

泪湿孤枕 提交于 2019-12-14 02:21:35

问题


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:


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.



来源:https://stackoverflow.com/questions/15509828/java-running-external-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!