자바 동적 컴 파일 및 동적 로드 실현
7353 단어 자바 동적 컴 파일동적 로드
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;
}
자바 가 동적 컴 파일 을 실현 하고 동적 으로 불 러 오 는 것 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 자바 동적 컴 파일 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 코드 개선자바 의 동적 컴 파일 은 원본 에 여러 개의 경 로 를 제공 합 니 다.예 를 들 어 문자열(예 에서 문자열)일 수도 있 고 텍스트 파일 일 수도 있 으 며 컴 파일 된 바이트 파일(class 파일)일 수도 있 고...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.