动态编译java文件 动态加载java类 动态执行java类的main方法。
动态编译需要加载 JDK/lib/tools.jar
下面是代码:
- /*
- * IBM Confidential
- *
- * OCO Source Materials
- *
- * #ID# IBM CRL Supply Chain Management Research
- *
- * (C) Copyright IBM Corp. 2005, 2006
- *
- * The source code for this program is not published or otherwise divested of
- * its trade secrets.
- *
- */
- package test;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.lang.reflect.Method;
- import java.net.URL;
- import java.net.URLClassLoader;
- public class CompileTest
- {
- public static void main(String[] args)
- throws Exception
- {
- String className = "Test";
- File file = new File(new File(System.getProperty("user.dir")),
- className + ".java");
- StringBuffer sb = new StringBuffer();
- sb.append("public class " + className + " { \r\n");
- sb.append(" public static void main(java.lang.String[] args) throws Exception { \r\n");
- sb.append(" System.out.println(\"This is a class compiled. ");
- sb.append(" class: \" + " + className + ".class.newInstance()); \r\n");
- sb.append(" } \r\n");
- sb.append("} \r\n");
- FileOutputStream ous = new FileOutputStream(file);
- ous.write(sb.toString().getBytes());
- ous.close();
- String[] arguments = new String[] { "-d",
- System.getProperty("user.dir"), className + ".java" };
- // Compile
- int result = com.sun.tools.javac.Main.compile(arguments);
- System.out.println(result == 0 ? "Compiled successly" : "Failed");
- URL classpath = new URL("file:/" + System.getProperty("user.dir") + "/");
- URLClassLoader classLoader = new URLClassLoader(new URL[] { classpath });
- // Load
- Class testClass = classLoader.loadClass(className);
- Method mainMethod = testClass.getMethod("main",
- new Class[] { String[].class });
- // Invoke main(String[] args)
- System.out.println(mainMethod);
-
- testClass.newInstance();
- mainMethod.invoke(null, new Object[] { null });
- }
- }
运行结果:
Compiled successly
public static void Test.main(java.lang.String[]) throws java.lang.Exception
This is a class compiled. class: Test@fc9944
阅读(588) | 评论(0) | 转发(0) |