动态生成JAVA代码(三)

该例不是直接使用javac,而是使用tools.jar

/*
?* 创建日期 2004-7-2
?* 创建人 HongSoft
?* 文件名 TestCompile.java
?*/
package com.hongsoft.test;

import java.io.*;

//定制的类装入器
public class MyCompile extends ClassLoader
{
?String _classpath;

?public static void main(String[] args)
?{

??new TestCompile();
?}

?public MyCompile()
?{
??super(ClassLoader.getSystemClassLoader());
??//编译器类型??
??_classpath = ".";
??String extraclasspath =
???"c://Program Files//Java//j2re1.4.2//lib//rt.jar";
??// = System.getProperty("calc.classpath");
??if (extraclasspath != null)
??{
???_classpath =
????_classpath
?????+ System.getProperty("path.separator")
?????+ extraclasspath;
??}
??compile();
?}

?public void compile()
?{
??// A3???????
??String filename = "";
??String classname = "";
??try
??{
???//创建临时文件
???File javafile =
????File.createTempFile("compiled_", ".java", new File("."));
???filename = javafile.getName();
???classname = filename.substring(0, filename.lastIndexOf("."));
???generateJavaFile(javafile, classname);
???//编译文件
???invokeCompiler(javafile);
???//创建java类
???byte[] buf = readBytes("d://" + classname + ".class");
???Class c = defineClass(buf, 0, buf.length);
???try
???{
????// 创建并返回类的实例
????//return (Calculator)
????c.newInstance();
???}
???catch (IllegalAccessException e)
???{
????throw new RuntimeException(e.getMessage());
???}
???catch (InstantiationException e)
???{
????throw new RuntimeException(e.getMessage());
???}
??}
??catch (IOException e)
??{
???throw new RuntimeException(e.getMessage());
??}
?}

?//生成java文件
?void generateJavaFile(File javafile, String classname) throws IOException
?{
??FileOutputStream out = new FileOutputStream(javafile);
??String text =
???"public class "
????+ classname
????+ " {"
????+ " public int getCreater() {return 1;}"
????+ "}";
??out.write(text.getBytes());
??out.close();
?}

?//编译java文件
?void invokeCompiler(File javafile) throws IOException
?{
??String[] cmd =
???{ "-classpath", _classpath, "-d", "d://", javafile.getName()};
??//执行编译命令
??int val = new com.sun.tools.javac.Main().compile(cmd);

??if (val != 0)
??{
???throw new RuntimeException("编译错误:" + "错误代码" + val);
??}
?}

?//以byte数组形式读入类文件
?byte[] readBytes(String filename) throws IOException
?{
??// A2
??File classfile = new File(filename);
??byte[] buf = new byte[(int) classfile.length()];
??FileInputStream in = new FileInputStream(classfile);
??in.read(buf);
??in.close();
??return buf;
?}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值