Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java to dynamically compile and load dynamically

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to use Java to dynamically compile and load dynamically. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

There is a java file in the test directory of disk D: AlTest.java

Public class AlTest {public String sayHello () {System.out.println ("AlTest class sayHello () method is executing...."); return "hello word";}}

Now it is necessary to compile the java file to the class file and run the method of the AlTest class when the project is already running.

Package com.piao.job; import java.lang.reflect.Method;import javax.tools.JavaCompiler;import javax.tools.ToolProvider;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Configurable;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component; @ Component@Configurable@EnableSchedulingpublic class CompilerJob {private static final Logger logger = LoggerFactory.getLogger (CompilerJob.class); private static boolean isExecute = false / * * * Task: job test * / @ Scheduled (cron = "* / 10 *") public void test2 () {try {if (isExecute) {return;} isExecute = true; / / just a test, so only execute complierAndRun () once } catch (Exception e) {logger.error ("test", e);}} public void complierAndRun () {try {System.out.println (System.getProperty ("user.dir")); / / dynamic compilation JavaCompiler javac = ToolProvider.getSystemJavaCompiler () Int status = javac.run (null, "- d", System.getProperty ("user.dir") + "\ target\ classes", "D:/test/AlTest.java"); if (statuscompiler 0) {System.out.println ("not compiled successfully!") ;} / / dynamically executes Class clz = Class.forName ("AlTest"); / / returns the Class object associated with the class or interface with the given string name. Object o = clz.newInstance (); Method method = clz.getDeclaredMethod ("sayHello"); / / returns a Method object that reflects the specified declared method String result= (String) method.invoke (o) of the class or interface represented by this Class object; / / the first parameter of the static method can be null, and the second parameter can be the actual parameter System.out.println (result) } catch (Exception e) {logger.error ("test", e);}

Running result:

E:zhoufysmallpiao-admin

The AlTest class sayHello () method is being executed.

Hello word

Where the code is:

Int status = javac.run (null, "- d", System.getProperty ("user.dir") + "\ target\ classes", "D:/test/AlTest.java")

The class file is generated to the classes directory (E:zhoufysmallpiao-admin argetclassess) under the current project directory, so classloader can be loaded into it. If you want to know which classloader it is:

Class clz = Class.forName ("AlTest"); / / returns the Class object associated with the class or interface with the given string name.

Object o = clz.newInstance ()

System.out.println (clz.getClassLoader () .getSystemClassLoader ())

What is printed is: sun.misc.Launcher$AppClassLoader@4e0e2f2a instructions using AppClassLoader

Of course, it can also be generated to a directory that can be loaded by Bootstrap ClassLoader.

/ / generate to project classes / / int status = javac.run (null, "- d", System.getProperty ("user.dir") + "\ target\ classes", "D:/test/AlTest.java") / / generate to BootStrap ClassLoader loadable directory int status = javac.run (null, "- d", "C:\ Program Files\ Java\ jdk1.8.0_65\ jre\ classes", "D:/test/AlTest.java")

Of course, you can also customize the classloader to generate files in a specified external directory:

Public void complierAndRun () {try {System.out.println (System.getProperty ("user.dir")); / / dynamic compilation JavaCompiler javac = ToolProvider.getSystemJavaCompiler () Int status = javac.run (null, "- d", "D:\", "D:/test/AlTest.java"); if (statuscompiler 0) {System.out.println ("not compiled successfully!") ;} / dynamically execute / / Class clz = Class.forName ("AlTest"); / / returns the Class object associated with the class or interface with the given string name. / / Custom classloader load path MyClassLoader myClassLoader = new MyClassLoader ("D:\"); / / package name + class name Class clz = myClassLoader.loadClass ("AlTest"); Object o = clz.newInstance (); Method method = clz.getDeclaredMethod ("sayHello") / / returns a Method object that reflects the specified declared method String result= (String) method.invoke (o) of the class or interface represented by this Class object; / / the first parameter of the static method can be null, and the second parameter can be the actual parameter System.out.println (result) } catch (Exception e) {logger.error ("test", e);}}

Java code that executes code dynamically, java eval

Public class ScriptUtils {private static final Logger logger = LoggerFactory.getLogger (ScriptUtils.class); / *

Perform string calculation

* @ param express * @ param params * @ return * @ throws ScriptException * / @ SuppressWarnings ("unchecked") public static E eval (String express, Map params) throws ScriptException {ScriptEngineManager manager = new ScriptEngineManager (); ScriptEngine engine = manager.getEngineByName ("js"); if (params = = null) {params = new HashMap ();} Iterator iter = params.entrySet (). Iterator () Map.Entry entry = null; while (iter.hasNext ()) {entry = iter.next (); engine.put (entry.getKey (), entry.getValue ());} E result = null; try {result = (E) engine.eval (express) } catch (ScriptException e) {logger.warn ("expression execution exception:" + e.getMessage ());} return result } / * parses the string and executes it as an expression * @ param express * @ param params * @ return * @ throws ScriptException * / public static Boolean evalBoolean (String express, Map params) {ScriptEngineManager manager = new ScriptEngineManager (); ScriptEngine engine = manager.getEngineByName ("js") If (params = = null) {params = new HashMap ();} Iterator iter = params.entrySet (). Iterator (); Map.Entry entry = null; while (iter.hasNext ()) {entry = iter.next (); engine.put (entry.getKey (), entry.getValue ());} Boolean result = null Try {result = (Boolean) engine.eval (express);} catch (ScriptException e) {result = false; logger.warn ("expression execution exception:" + e.getMessage ());} return result;} Thank you for reading! On "how to use Java to achieve dynamic compilation and dynamic loading" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report