java 脚本_java 脚本解释器

如果用过python,就知道它有了command line 工具,比如你输入 print 'a' ,该工具输出:a,好处是便于快速学习python 语法。

其实java也可以做到。

下面是一个java 脚本解释器的helloword版本,思路如下:

1动态创建一个Temp.java类文件,里面只有一个excute方法,把从控制台输入 的字符串加入到类方法中,比如for(int i=0;i<10;i++){System.out.println(i);}。

2再利用com.sun.tools.javac.Main.compile 动态编译Temp.java 生成class

3将Temp.class载入到jvm

4生成object实例,利用反射执行excute方法

说明,这只是个test版本。

public class Test {

public static void main(String[] args)

throws IOException, ClassNotFoundException, InstantiationException,

IllegalAccessException, IllegalArgumentException, SecurityException,

InvocationTargetException, NoSuchMethodException{

BufferedReader reader  = new BufferedReader(new InputStreamReader(System.in));

while(true){

String js=reader.readLine();

OutputStream os = new FileOutputStream("Temp.java");

String tempJava="public class Temp"+

" {   "+

" public void excute() "+

" {  "+

js+

" }  "+

" }  ";

os.write(tempJava.getBytes());

os.close();

String[] compileArgs = new String[] {"Temp.java"};

com.sun.tools.javac.Main.compile(compileArgs);

URLClassLoader loader =

new URLClassLoader(new URL[]{new File(".").toURI().toURL()});

Class> scriptClass = loader.loadClass("Temp");

Object obj = scriptClass.newInstance();

obj.getClass().getDeclaredMethod("excute").invoke(obj);

obj=null;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值