자바 동적 컴 파일 및 동적 로드 실현

D 디스크 test 디 렉 터 리 아래 자바 파일 이 있 습 니 다:AlTest.자바

public class AlTest { 
	public String sayHello(){
		System.out.println("AlTest  sayHello()      ....");
		return "hello word";
	}
}
프로젝트 가 실 행 된 과정 에서 자바 파일 을 class 파일 로 컴 파일 하고 AlTest 클래스 를 실행 하 는 방법 이 필요 합 니 다.

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
@EnableScheduling
public class CompilerJob {
 
  private static final Logger logger = LoggerFactory.getLogger(CompilerJob.class);
 
  private static boolean isExecute = false;
 
  /**
   *   :job test
   */
  @Scheduled(cron = "*/10 * * * * * ")
  public void test2() {
    try {
       if (isExecute) {
         return;
       }
       isExecute = true;		//    ,       
			
	   complierAndRun();
	} catch (Exception e) {
	   logger.error("test", e);
	}
  }
	
 public void complierAndRun(){
   try {
			
	 System.out.println(System.getProperty("user.dir"));
	 //    
	 JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
	 int status = javac.run(null, null, null, "-d", System.getProperty("user.dir")+"\\target\\classes","D:/test/AlTest.java");
	 if(status!=0){
		 System.out.println("      !");
	 }
			
	 //    
	 Class clz = Class.forName("AlTest");//                      Class   。
	 Object o = clz.newInstance();
	 Method method = clz.getDeclaredMethod("sayHello");//     Method   ,       Class                   
	 String result= (String)method.invoke(o);//           null,          
	 System.out.println(result);
	 } catch (Exception e) {
		 logger.error("test", e);
	 }
  }
}
실행 결과:
E:\zhoufy\small\piao-admin
AlTest 클래스 sayHello()방법 이 실행 중 입 니 다...
hello word
그 중 코드:
 int status = javac.run(null, null, null, "-d", System.getProperty("user.dir")+"\\target\\classes","D:/test/AlTest.java");
class 파일 을 현재 프로젝트 디 렉 터 리 에 있 는 classes 디 렉 터 리(E:\zhoufy\small\piao-admin\\target\classes)로 생 성 했 기 때문에 classloader 는 불 러 올 수 있 습 니 다.어떤 종류의 로 더 인지 알 고 싶다 면:
Class clz = Class.forName("AlTest");//주어진 문자열 이름 을 가 진 클래스 나 인터페이스 와 연 결 된 Class 대상 을 되 돌려 줍 니 다.
Object o = clz.newInstance();
System.out.println(clz.getClassLoader().getSystemClassLoader());
인쇄 된 것 은:sun.misc.Launcher$AppClassLoader@4e0e2f2a설명 은 AppClassLoader 를 사용 합 니 다.
물론 Bootstrap ClassLoader 가 불 러 올 수 있 는 디 렉 터 리 에 도 생 성 할 수 있 습 니 다.

//     classes 
//int status = javac.run(null, null, null, "-d", System.getProperty("user.dir")+"\\target\\classes","D:/test/AlTest.java");
			
//   BootStrap ClassLoader      
int status = javac.run(null, null, null, "-d", "C:\\Program Files\\Java\\jdk1.8.0_65\\jre\\classes","D:/test/AlTest.java");
물론 클래스 로 더 를 사용자 정의 하여 지정 한 외부 디 렉 터 리 에 파일 을 생 성 할 수 있 습 니 다.

public void complierAndRun(){
		try {
			
			System.out.println(System.getProperty("user.dir"));
			 //    
			JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
			int status = javac.run(null, null, null, "-d", "D:\\","D:/test/AlTest.java");
			if(status!=0){
				System.out.println("      !");
			}
			
			//    
			//Class clz = Class.forName("AlTest");//                      Class   。
			//            
			MyClassLoader myClassLoader = new MyClassLoader("D:\\");
			//  +  
			Class clz = myClassLoader.loadClass("AlTest");
			Object o = clz.newInstance();
			Method method = clz.getDeclaredMethod("sayHello");//     Method   ,       Class                   
			String result= (String)method.invoke(o);//           null,          
			System.out.println(result);
		} catch (Exception e) {
			logger.error("test", e);
		}
	}
자바 동적 실행 코드,자바 eval

public class ScriptUtils {
     
    private static final Logger logger = LoggerFactory.getLogger(ScriptUtils.class);
     
    /**
     * 
     * <p>       </p>
     * @param express
     * @param params
     * @return
     * @throws ScriptException 
     */
    @SuppressWarnings("unchecked")
    public static <T, E> E eval(String express, Map<String, T> params) throws ScriptException{
        ScriptEngineManager manager = new ScriptEngineManager();  
        ScriptEngine engine = manager.getEngineByName("js");
        if(params == null){
            params = new HashMap<String,T>();
        }
        Iterator<Map.Entry<String, T>> iter = params.entrySet().iterator();
        Map.Entry<String, T> 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("       : " + e.getMessage());
        } 
        return result;
    }
     
    /**
     *      ,           
     * @param express
     * @param params
     * @return
     * @throws ScriptException
     */
    public static <T> Boolean evalBoolean(String express, Map<String, T> params) {
        ScriptEngineManager manager = new ScriptEngineManager();  
        ScriptEngine engine = manager.getEngineByName("js");
        if(params == null){
            params = new HashMap<String,T>();
        }
        Iterator<Map.Entry<String, T>> iter = params.entrySet().iterator();
        Map.Entry<String, T> 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("       : " + e.getMessage());
        } 
        return result;
    }
자바 가 동적 컴 파일 을 실현 하고 동적 으로 불 러 오 는 것 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 자바 동적 컴 파일 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기