自定义运行器以及编译器

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 初始化");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ljt-tiger

thanks

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值