java - Calling custom method of a class compiled at runtime -
i have java source code compiled @ runtime. i'm compiling source code (present string) , loading class below :
javacompiler compiler = toolprovider.getsystemjavacompiler(); compiler.run(null, null, null, sourcefile.getpath()); // load , instantiate compiled class. urlclassloader classloader = urlclassloader.newinstance(new url[] { root.touri().tourl() }); class<?> cls = class.forname("takeadvantageoftmapcomponents", true, classloader);
this class contains method need call named runjob
. i'd like:
takeadvantageoftmapcomponents c = new takeadvantageoftmapcomponents(); c.runjob(new string[]);
now same method present in class compile @ runtime. how call ?
better using reflection call method want, might want declare interface
class extend, such as:
package ccjmne; public interface jobrunner { public void runjob(final string[] args); }
... , make class implement interface
:
file: /home/eric/stackoverflow/a.java
package stackoverflow; public class implements ccjmne.jobrunner { public void runjob(final string args[]) { for(final string str : args) { system.out.println(str); } } }
and finally, load class follows:
final class<jobrunner> cls = (class<jobrunner>) class.forname("stackoverflow.a", true, classloader);
note know i've jobrunner
here.
thus, can do:
cls.newinstance().runjob("hello world!".split(" "));
... , you're done!
sample working code:
package ccjmne; import java.io.file; import java.net.malformedurlexception; import java.net.url; import java.net.urlclassloader; import javax.tools.javacompiler; import javax.tools.toolprovider; public class jobrunnertest { public static void main(final string[] args) throws classnotfoundexception, instantiationexception, illegalaccessexception, malformedurlexception { final javacompiler compiler = toolprovider.getsystemjavacompiler(); final file root = new file("/home/eric/"); compiler.run(null, null, null, root + "/stackoverflow/a.java"); final urlclassloader classloader = urlclassloader.newinstance(new url[] { root.touri().tourl() }); final class<jobrunner> cls = (class<jobrunner>) class.forname("stackoverflow.a", true, classloader); cls.newinstance().runjob("hello world!".split(" ")); } }
output:
hello world!
Comments
Post a Comment