Skip to content

Commit d35524f

Browse files
author
yongjie.zhang
committed
java脚本交互引擎Rhino以及字节码操作javassist
1 parent d5a9159 commit d35524f

File tree

7 files changed

+253
-0
lines changed

7 files changed

+253
-0
lines changed

java-Javassist/java-Javassist.iml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
7+
</content>
8+
<orderEntry type="inheritedJdk" />
9+
<orderEntry type="sourceFolder" forTests="false" />
10+
<orderEntry type="module-library" exported="">
11+
<library>
12+
<CLASSES>
13+
<root url="jar://$USER_HOME$/Desktop/jboss-javassist-javassist-85d69ea/javassist.jar!/" />
14+
</CLASSES>
15+
<JAVADOC />
16+
<SOURCES />
17+
</library>
18+
</orderEntry>
19+
</component>
20+
</module>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.zyj.javassist;
2+
3+
import javassist.*;
4+
5+
import java.io.IOException;
6+
7+
/**
8+
* 版权声明:CopyRight (c) 2018 ucarinc. All Rights Reserved.
9+
*
10+
* @author : 张勇杰
11+
* @date : 2018/12/1 13:39
12+
* @Version : v1.0
13+
* @description
14+
**/
15+
public class Demo01 {
16+
public static void main(String[] args) throws CannotCompileException, NotFoundException, IOException {
17+
ClassPool pool = ClassPool.getDefault();
18+
CtClass cc = pool.makeClass("com.zyj.bean.Emp");
19+
20+
//创建属性
21+
CtField f1 = CtField.make("private int empno;", cc);
22+
CtField f2 = CtField.make("private String ename;", cc);
23+
cc.addField(f1);
24+
cc.addField(f2);
25+
26+
//创建方法
27+
CtMethod m1 = CtMethod.make("public int getEmpno(){return empno;}", cc);
28+
CtMethod m2 = CtMethod.make("public void setEmpno(int empno){this.empno=empno;}",cc);
29+
cc.addMethod(m1);
30+
cc.addMethod(m2);
31+
32+
//添加构造器
33+
CtConstructor constructor = new CtConstructor(new CtClass[]{CtClass.intType,pool.get("java.lang.String")},cc);
34+
constructor.setBody("{this.empno = empno;this.ename = ename;}");
35+
cc.addConstructor(constructor);
36+
cc.writeFile("c:/myjava");//将上面构造好的类写入到c:/myjava中
37+
}
38+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.zyj.javassist;
2+
3+
import javassist.*;
4+
5+
import java.io.IOException;
6+
import java.lang.reflect.Method;
7+
import java.text.MessageFormat;
8+
import java.util.Arrays;
9+
10+
/**
11+
* 版权声明:CopyRight (c) 2018 ucarinc. All Rights Reserved.
12+
*
13+
* @author : 张勇杰
14+
* @date : 2018/12/1 14:04
15+
* @Version : v1.0
16+
* @description 测试javassist的API
17+
**/
18+
public class Demo02 {
19+
/**
20+
* 处理类的基本用法
21+
*/
22+
public static void test01() throws IOException, CannotCompileException, NotFoundException {
23+
ClassPool pool = ClassPool.getDefault();
24+
CtClass cc = pool.get("com.zyj.javassist.Emp");
25+
26+
byte[] bytes = cc.toBytecode();
27+
System.out.println(Arrays.toString(bytes));
28+
29+
System.out.println(cc.getName());//获得类名
30+
System.out.println(cc.getSimpleName());//获得简要类名
31+
System.out.println(cc.getSuperclass());//获得父类
32+
System.out.println(cc.getInterfaces());//获得接口
33+
}
34+
35+
/**
36+
* 测试产生新的方法
37+
*/
38+
public static void test02() throws Exception {
39+
ClassPool pool = ClassPool.getDefault();
40+
CtClass cc = pool.get("com.zyj.javassist.Emp");
41+
//CtMethod m = CtNewMethod.make("public int add(int a,int b){return a+b}",cc);
42+
43+
CtMethod m = new CtMethod(CtClass.intType,"add",new CtClass[]{CtClass.intType,CtClass.intType},cc);
44+
m.setModifiers(Modifier.PUBLIC);
45+
m.setBody("{return $1+$2;}");
46+
cc.addMethod(m);
47+
48+
//通过反射调用新生成的方法
49+
Class clazz = cc.toClass();
50+
Object obj = clazz.newInstance();//通过调用mp无参构造器,创建新的Emp对象
51+
Method method = clazz.getDeclaredMethod("add",int.class,int.class);
52+
Object o = method.invoke(obj, 1, 1);
53+
System.out.println(o);
54+
55+
}
56+
57+
58+
public static void test03()throws Exception{
59+
ClassPool pool = ClassPool.getDefault();
60+
CtClass cc = pool.get("com.zyj.javassist.Emp");
61+
62+
CtMethod cm = cc.getDeclaredMethod("sayHello",new CtClass[]{CtClass.intType});
63+
cm.insertBefore("System.out.println($1);System.out.println(\"start!!!\");");
64+
65+
//通过反射调用新生成的方法
66+
Class clazz = cc.toClass();
67+
Object obj = clazz.newInstance();
68+
Method m = clazz.getDeclaredMethod("sayHello",int.class);
69+
Object result = m.invoke(obj, 1111);
70+
System.out.println(result);
71+
72+
}
73+
public static void main(String[] args) throws Exception {
74+
test03();
75+
}
76+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.zyj.javassist;
2+
3+
/**
4+
* 版权声明:CopyRight (c) 2018 ucarinc. All Rights Reserved.
5+
*
6+
* @author : 张勇杰
7+
* @date : 2018/12/1 13:39
8+
* @Version : v1.0
9+
* @description
10+
**/
11+
public class Emp {
12+
private String empno;
13+
private String ename;
14+
public void sayHello(int a){
15+
System.out.println("sayHello"+a);
16+
}
17+
18+
public Emp(String empno, String ename) {
19+
this.empno = empno;
20+
this.ename = ename;
21+
}
22+
23+
public Emp() {
24+
}
25+
26+
public String getEmpno() {
27+
return empno;
28+
}
29+
30+
public void setEmpno(String empno) {
31+
this.empno = empno;
32+
}
33+
34+
public String getEname() {
35+
return ename;
36+
}
37+
38+
public void setEname(String ename) {
39+
this.ename = ename;
40+
}
41+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
7+
</content>
8+
<orderEntry type="inheritedJdk" />
9+
<orderEntry type="sourceFolder" forTests="false" />
10+
</component>
11+
</module>

java-scriptEngineRhino/src/a.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
function test() {
2+
var a =3;
3+
var b = 4;
4+
print("invoke js file:"+(a+b));
5+
6+
}
7+
test();
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.zyj.rhino;
2+
3+
import javax.script.Invocable;
4+
import javax.script.ScriptEngine;
5+
import javax.script.ScriptEngineManager;
6+
import javax.script.ScriptException;
7+
import java.io.FileReader;
8+
import java.net.URL;
9+
import java.util.List;
10+
11+
/**
12+
* 版权声明:CopyRight (c) 2018 ucarinc. All Rights Reserved.
13+
*
14+
* @author : 张勇杰
15+
* @date : 2018/11/28 12:52
16+
* @Version : v1.0
17+
* @description 测试脚本引擎执行javascript代码
18+
**/
19+
public class Demo01 {
20+
public static void main(String[] args) throws Exception {
21+
//获得脚本引擎对象
22+
ScriptEngineManager sem = new ScriptEngineManager();
23+
ScriptEngine engine = sem.getEngineByName("javascript");
24+
25+
//定义变量,存储到引擎上下文
26+
engine.put("msg","zhangyongjie is a good man!");
27+
String str = "var user = {name:'zhangyongjie',age:18,schools:['诸暨中学','温州大学']};";
28+
str += "print(user.name);";
29+
30+
//执行脚本
31+
engine.eval(str);
32+
engine.eval("msg = 'sxt is a bad school';");
33+
System.out.println(engine.get("msg"));
34+
35+
System.out.println("*************************");
36+
//定义函数
37+
engine.eval("function add(a,b){var sum = a+b; return sum;}");
38+
//取得调用接口
39+
Invocable jsInvoke = (Invocable) engine;
40+
//执行脚本中定义的方法
41+
Object obj = jsInvoke.invokeFunction("add",1,2);
42+
System.out.println(obj);
43+
44+
//导入其他java包,使用其他保重的java类
45+
//java1.8之后要这么写。
46+
String jsCode = "var list = java.util.Arrays.asList(\"温州大学\",\"诸暨中学\")";
47+
engine.eval(jsCode);
48+
List<String> list = (List<String>) engine.get("list");
49+
for(String a:list){
50+
System.out.println(a);
51+
}
52+
53+
//执行一个js文件(将a.js置于项目的src下即可
54+
URL url = Demo01.class.getClassLoader().getResource("a.js");
55+
System.out.println(url);
56+
FileReader fr = new FileReader(url.getPath());
57+
engine.eval(fr);
58+
fr.close();
59+
}
60+
}

0 commit comments

Comments
 (0)