Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1693977
  • 博文数量: 347
  • 博客积分: 9328
  • 博客等级: 中将
  • 技术积分: 2680
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-29 23:45
文章分类

全部博文(347)

文章存档

2016年(1)

2013年(4)

2012年(207)

2011年(85)

2010年(50)

分类: Java

2012-05-28 22:52:52

动态编译java文件 动态加载java类 动态执行java类的main方法。

动态编译需要加载 JDK/lib/tools.jar

下面是代码:

点击(此处)折叠或打开

  1. /*
  2.  * IBM Confidential
  3.  *
  4.  * OCO Source Materials
  5.  *
  6.  * #ID# IBM CRL Supply Chain Management Research
  7.  *
  8.  * (C) Copyright IBM Corp. 2005, 2006
  9.  *
  10.  * The source code for this program is not published or otherwise divested of
  11.  * its trade secrets.
  12.  *
  13.  */
  14.  package test;

  15. import java.io.File;
  16.  import java.io.FileOutputStream;
  17.  import java.lang.reflect.Method;
  18.  import java.net.URL;
  19.  import java.net.URLClassLoader;

  20. public class CompileTest
  21.  {

  22.     public static void main(String[] args)
  23.              throws Exception
  24.      {
  25.          String className = "Test";

  26.         File file = new File(new File(System.getProperty("user.dir")),
  27.                  className + ".java");

  28.         StringBuffer sb = new StringBuffer();

  29.         sb.append("public class " + className + " { \r\n");
  30.          sb.append(" public static void main(java.lang.String[] args) throws Exception { \r\n");
  31.          sb.append(" System.out.println(\"This is a class compiled. ");
  32.          sb.append(" class: \" + " + className + ".class.newInstance()); \r\n");
  33.          sb.append(" } \r\n");
  34.          sb.append("} \r\n");

  35.         FileOutputStream ous = new FileOutputStream(file);
  36.          ous.write(sb.toString().getBytes());
  37.          ous.close();

  38.         String[] arguments = new String[] { "-d",
  39.                  System.getProperty("user.dir"), className + ".java" };

  40.         // Compile
  41.          int result = com.sun.tools.javac.Main.compile(arguments);

  42.         System.out.println(result == 0 ? "Compiled successly" : "Failed");

  43.         URL classpath = new URL("file:/" + System.getProperty("user.dir") + "/");

  44.         URLClassLoader classLoader = new URLClassLoader(new URL[] { classpath });

  45.         // Load
  46.          Class testClass = classLoader.loadClass(className);

  47.         Method mainMethod = testClass.getMethod("main",
  48.                  new Class[] { String[].class });

  49.         // Invoke main(String[] args)
  50.          System.out.println(mainMethod);
  51.          
  52.          testClass.newInstance();

  53.         mainMethod.invoke(null, new Object[] { null });

  54.     }
  55.  }



运行结果:

Compiled successly
 public static void Test.main(java.lang.String[]) throws java.lang.Exception
 This is a class compiled.              class: Test@fc9944
阅读(1387) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~