public class Demo01 {
public static void main(String[] args) {
JavaCompiler compiler= ToolProvider.getSystemJavaCompiler();
int result=compiler.run(null, null, null,"d:/myC/HelloWorld.java");
System.out.println(result==0?"编译成功":"编译失败");
String str="public class HelloWorld{\n" +
"\tpublic static void main(String[] args){\n" +
"\t\tSystem.out.println(\"helloworld\");\n" +
"\t}\n" +
"}";
}
}
public class Demo01 {
public static void main(String[] args) throws IOException {
//JavaCompiler编译类
JavaCompiler compiler= ToolProvider.getSystemJavaCompiler();
int result=compiler.run(null, null, null,"d:/myC/HelloWorld.java");
System.out.println(result==0?"编译成功":"编译失败");
String str="public class HelloWorld{\n" +
"\tpublic static void main(String[] args){\n" +
"\t\tSystem.out.println(\"helloworld\");\n" +
"\t}\n" +
"}";
final File htmlFile = File.createTempFile("tmp", ".java");//创建临时文件
System.out.println("临时文件所在的本地路径:" + htmlFile.getCanonicalPath());
BufferedWriter bw = new BufferedWriter(new FileWriter(htmlFile));
result=compiler.run(null, null, null,htmlFile.getCanonicalPath());
System.out.println(result==0?"编译成功":"编译失败");
try {
bw.write(str);
bw.flush();
} finally {
bw.close();
htmlFile.deleteOnExit();//程序退出时删除临时文件
}
//Runtime调用编译类
Runtime run=Runtime.getRuntime();
Process process=run.exec("java -cp d:/myC HelloWorld");
InputStream in=process.getInputStream();
BufferedReader bw1=new BufferedReader(new InputStreamReader(in));
String info="";
while((info=bw1.readLine())!=null){
System.out.println(info);
}
}
}
public static void runJavaClassByReflect() throws Exception{
try {
URL[] urls = new URL[] {new URL("file:/"+"d:/myC/")};
URLClassLoader loader = new URLClassLoader(urls);
Class c = loader.loadClass("HelloWorld");
//调用加载类的main方法
c.getMethod("main",String[].class).invoke(null, (Object)new String[]{});
} catch (Exception e) {
e.printStackTrace();
}
}
字节码操作:
/**
* 测试javassist的类
*/
public class Demo01 {
public static void main(String[] args) throws CannotCompileException, NotFoundException, IOException {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.makeClass("ssist.Emp");
//创建属性
CtField f1=CtField.make("private int empNum;", cc);
CtField f2=CtField.make("private String ename;", cc);
cc.addField(f1);
cc.addField(f2);
//创建方法
CtMethod m1=CtMethod.make("public int getEmpNum(){return empNum;}", cc);
CtMethod m2=CtMethod.make("public void setEmpNum(int empNum){this.empNum=empNum;};", cc);
cc.addMethod(m1);
cc.addMethod(m2);
//添加构造器
CtConstructor constructor=new CtConstructor(new CtClass[]{CtClass.intType,pool.get("java.lang.String")}, cc);
constructor.setBody("{this.empNum=empNum;this.ename=ename;}");
cc.addConstructor(constructor);
//写入到文件
cc.writeFile("d:/myJava");
}
}
/**
* 测试api
*/
public class Demo02 {
public static void test() throws NotFoundException, IOException, CannotCompileException {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("ssist.Emp");
byte[] bytes=cc.toBytecode();
System.out.println(Arrays.toString(bytes));
System.out.println(cc.getName());
//获取简要类名
System.out.println(cc.getSimpleName());
//获取父类
System.out.println(cc.getSuperclass());
//获取接口
System.out.println(cc.getInterfaces());
}
/**
* 测试产生新的方法
*/
public static void tets02() throws CannotCompileException, IllegalAccessException, InstantiationException, NotFoundException, InvocationTargetException, NoSuchMethodException {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("ssist.Emp");
// CtMethod m=CtNewMethod.make("public int add(int a,int b){return a+b;}",cc);
CtMethod m=new CtMethod(CtClass.intType, "add", new CtClass[]{CtClass.intType,CtClass.intType},cc);
m.setModifiers(Modifier.PUBLIC);
m.setBody("{System.out.println(\"lsd is a good boy\");return $1+$2;}");
cc.addMethod(m);
//通过反射调用刚新生成的方法
Class clazz=cc.toClass();
Object obj=clazz.newInstance();
Method m1=clazz.getDeclaredMethod("add",int.class,int.class);
Object result=m1.invoke(obj,10,20);
System.out.println(result);
}
/**
* 修改属性信息
* @throws NotFoundException
* @throws CannotCompileException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
public static void test03() throws NotFoundException, CannotCompileException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("ssist.Emp");
CtMethod m=cc.getDeclaredMethod("sayHello", new CtClass[]{CtClass.intType});
//修改方法前面的内容
m.insertBefore("System.out.println($1);System.out.println(\"start\");");
m.insertAt(8, "int b=2;System.out.println(b);");
//修改方法后面的内容
m.insertAfter("System.out.println(\"end\");");
Class clazz=cc.toClass();
Object obj=clazz.newInstance();
Method m1=clazz.getDeclaredMethod("sayHello",int.class);
m1.invoke(obj,10);
}
/**
* 添加属性
* @throws Exception
*/
public static void test04() throws Exception{
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("ssist.Emp");
//设置属性
CtField f1=new CtField(CtClass.intType, "salary",cc);
f1.setModifiers(Modifier.PRIVATE);
cc.addField(f1);
//添加方法
cc.addMethod(CtNewMethod.getter("getSalart", f1));
cc.addMethod(CtNewMethod.setter("SetSalart", f1));
}
//构造器
public static void test5() throws Exception {
ClassPool pool=ClassPool.getDefault();
CtClass cc=pool.get("ssist.Emp");
CtConstructor[] constructors=cc.getConstructors();
for(CtConstructor constructor:constructors){
System.out.println(constructor);
}
}
public static void main(String[] args) throws Exception {
test5();
}
}