运用JDK动态编译java字符串ITeye - 凯时娱乐

运用JDK动态编译java字符串ITeye

2019-01-13 05:48:32 | 作者: 静枫 | 标签: 动态,加载,途径 | 浏览: 2037

try { // 例如/usr/java/classes下有一个test.App类,则/usr/java/classes即这个类的根途径,而.class文件的实践方位是/usr/java/classes/test/App.class File clazzPath = new File(basePath); // 记载加载.class文件的数量 int clazzCount = 0; if (clazzPath.exists() clazzPath.isDirectory()) { // 获取途径长度 int clazzPathLen = clazzPath.getAbsolutePath().length() + 1; Stack File stack = new Stack (); stack.push(clazzPath); // 遍历类途径 while (stack.isEmpty() == false) { File path = stack.pop(); File[] classFiles = path.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory() || pathname.getName().endsWith(".class"); for (File subFile : classFiles) { if (subFile.isDirectory()) { stack.push(subFile); } else { if (clazzCount++ == 0) { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); boolean accessible = method.isAccessible(); try { if (accessible == false) { method.setAccessible(true); // 设置类加载器 URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); // 将当时类途径参加到类加载器 强制将累参加当时classpath中 method.invoke(classLoader, clazzPath.toURI().toURL()); } finally { method.setAccessible(accessible); // 文件名称 String className = subFile.getAbsolutePath(); className = className.substring(clazzPathLen, className.length() - 6); className = className.replace(File.separatorChar, .); // 加载Class类 SoaLogger.debug(QuartzManger.class,"动态加载[class:{"+className+"}]"); } catch (Exception e) { public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, JobExecutionException { String src = "package org.soa.quartz.api.job;"+ "public class Job5 implements org.quartz.Job {"+ "public void execute(org.quartz.JobExecutionContext context)"+ "throws org.quartz.JobExecutionException {"+ "System.out.println(\"我是动态增加的jobss\");"+ String src2 = "package liuyi.soa.quartz.api.job;"+ "public class Job5 implements org.quartz.Job {"+ "public void execute(org.quartz.JobExecutionContext context)"+ "throws org.quartz.JobExecutionException {"+ "System.out.println(\"我是动态增加的jobss\");"+ "}"+ "}"; final JdkCompiler jdkCompiler = JdkCompiler.INSTA; jdkCompiler.compile(Arrays.asList(src,src2),Arrays.asList("org.soa.quartz.api.job.Job5","liuyi.soa.quartz.api.job.Job5") ); jdkCompiler.compile(Arrays.asList(src,src2),Arrays.asList("org.soa.quartz.api.job.Job5","liuyi.soa.quartz.api.job.Job5") );
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表凯时娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章