1、编译:javac MyRunner.java
2、动态编译运行:java MyRunner Person prt
3、代码演示如下:
import java.io.*;
import java.lang.reflect.*;
/**
* 自定义运行器,继承ClassLoad类
* @author tiger
* @Date 2017年8月3日
*/
public class MyRunner extends ClassLoader{
/**
* 测试类
* 1、编译:javac MyRunner.java
* 2、动态编译运行:java MyRunner Person prt
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//获取类名
String className = args[0];
//获取方法名
String mName = args[1];
//首先编译
MyCompiler compiler = new MyCompiler();
compiler.doCompile(className);
//延时一下确保编译已经完成
Thread.sleep(5000);
//运行
MyRunner r = new MyRunner();
Class
clazz = r.findClass(className);
r.running(clazz, mName);
}
/**
* 从编译好的.class文件中获取字节码数据
* @param name
* @return
* @throws IOException
*/
public byte[] getRawsData(String name) throws IOException{
InputStream is = new FileInputStream(name+".class");
byte[] buf = new byte[is.available()];
is.read(buf);
is.close();
return buf;
}
/**
* 重写父类 ClassLoader 的 findClass 方法
*/
@Override
protected Class
findClass( String name )
throws ClassNotFoundException{
byte[] raws = null;
try {
raws = getRawsData( name );
} catch (IOException e) {
e.printStackTrace();
} //拿到字节码的原数据
//调用父类 ----> ClassLoader 的 defineClass 来获取一个字节码对象
Class
clazz = defineClass( name, raws, 0, raws.length );
//返回加载到的 "字节码对象"
return clazz;
}
/**
* 运行编译好的类,执行相应的静态方法
* @param clzz 类的字节码
* @param mName 运行时执行的方法名
* @throws Exception
*/
public void running(Class
clazz,String mName)
throws Exception{
Method m = clazz.getMethod(mName);
//执行传入的方法
m.invoke(null);
}
}
import java.io.IOException;
/**
* 我的编译器
* @author tiger
* @Date 2017年8月3日
*/
public class MyCompiler {
public int doCompile( String file ) throws IOException{
Process p = Runtime.getRuntime().exec( "javac "+ file+".java");
try{
p.waitFor(); //等这一个程序的执行完成(阻塞)
}catch( InterruptedException e ){
e.printStackTrace();
}
return p.exitValue();
}
}
package com.reflect.compile;
/**
* 自定义运行器以及编译器
* @author tiger
* @Date 2017年8月3日
*/
public class Person {
public void prt(){
System.out.println("Person.prt()");
}
{
System.out.println("Person非静态person 初始化");
}
static{
System.out.println("Person静态 person 初始化");
}
}