博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 基础 -- javassist
阅读量:5242 次
发布时间:2019-06-14

本文共 6077 字,大约阅读时间需要 20 分钟。

 

 

 

package com.bdqn.service;/** * 使用javassist 生成一个新的类 *  */import java.io.IOException;import javassist.CannotCompileException;import javassist.ClassPool;import javassist.CtClass;import javassist.CtConstructor;import javassist.CtField;import javassist.CtMember;import javassist.CtMethod;import javassist.NotFoundException;public class Test { public static void main(String[] args) throws CannotCompileException, NotFoundException, IOException {            ClassPool pool = ClassPool.getDefault();        CtClass cc = pool.makeClass("com.bjsxt.bean.Emp");                //创建属性        CtField f1 = CtField.make("private int empno;//dasf", cc);        CtField f2 = CtField.make("private String ename;", cc);        cc.addField(f1);        cc.addField(f2);                //创建方法        CtMethod m1 = CtMethod.make("public int getEmpno(){return empno;}", cc);        CtMethod m2 = CtMethod.make("public void setEmpno(int empno){this.empno=empno;}", cc);        cc.addMethod(m1);        cc.addMethod(m2);                //添加构造器        CtConstructor constructor = new CtConstructor(new CtClass[]{CtClass.intType,pool.get("java.lang.String")}, cc);        constructor.setBody("{this.empno=empno; this.ename=ename;}");        cc.addConstructor(constructor);        cc.writeFile("c:/"); //将上面构造好的类写入到c:/myjava中        System.out.println("生成类,成功!");}}
dynamicwriter

 

package com.bdqn.service;import java.lang.reflect.Method;import java.util.Arrays;import javax.tools.JavaCompiler;import javax.tools.ToolProvider;import javassist.ClassPool;import javassist.CtClass;import javassist.CtConstructor;import javassist.CtField;import javassist.CtMethod;import javassist.CtNewMethod;import javassist.Modifier;public class Demo2 {    /**     * 处理类的基本用法     * @throws Exception      */    public static void test01() throws Exception{        ClassPool pool = ClassPool.getDefault();        CtClass cc = pool.get("com.bdqn.service.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()); //获得接口            }        /**     * 测试产生新的方法     * @throws Exception      */    public static void test02() throws Exception{        ClassPool pool = ClassPool.getDefault();        CtClass cc = pool.get("com.bjsxt.test.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(\"www.sxt.cn\");return $1+$2;}");                cc.addMethod(m);                //通过反射调用新生成的方法        Class clazz = cc.toClass();        Object obj = clazz.newInstance();  //通过调用Emp无参构造器,创建新的Emp对象        Method method = clazz.getDeclaredMethod("add", int.class,int.class);        Object result = method.invoke(obj, 200,300);        System.out.println(result);    }        /**     修改已有的方法的信息,修改方法体的内容     * @throws Exception     */    public static void test03() throws Exception{        ClassPool pool = ClassPool.getDefault();        CtClass cc = pool.get("com.bjsxt.test.Emp");                CtMethod cm = cc.getDeclaredMethod("sayHello",new CtClass[]{CtClass.intType});        cm.insertBefore("System.out.println($1);System.out.println(\"start!!!\");");        cm.insertAt(9, "int b=3;System.out.println(\"b=\"+b);");        cm.insertAfter("System.out.println(\"end!!!\");");                //通过反射调用新生成的方法        Class clazz = cc.toClass();        Object obj = clazz.newInstance();  //通过调用Emp无参构造器,创建新的Emp对象        Method method = clazz.getDeclaredMethod("sayHello", int.class);        method.invoke(obj, 300);    }    /**     * 属性的操作     * @throws Exception     */    public static void test04() throws Exception{        ClassPool pool = ClassPool.getDefault();        CtClass cc = pool.get("com.bjsxt.test.Emp");        //        CtField f1 = CtField.make("private int empno;", cc);        CtField f1 = new CtField(CtClass.intType,"salary",cc);        f1.setModifiers(Modifier.PRIVATE);        cc.addField(f1);        //        cc.getDeclaredField("ename");   //获取指定的属性                //增加相应的set和get方法        cc.addMethod(CtNewMethod.getter("getSalary", f1));;        cc.addMethod(CtNewMethod.getter("setSalary", f1));;            }        /**     * 构造方法的操作     * @throws Exception     */    public static void test05() throws Exception {        ClassPool pool = ClassPool.getDefault();        CtClass cc = pool.get("com.bjsxt.test.Emp");                CtConstructor[] cs = cc.getConstructors();        for (CtConstructor c : cs) {            System.out.println(c.getLongName());        }    }            public static void test06() throws Exception{         CtClass cc = ClassPool.getDefault().get("com.bjsxt.test.Emp");          Object[] all = cc.getAnnotations();         Author a = (Author)all[0];          String name = a.name();         int year = a.year();         System.out.println("name: " + name + ", year: " + year);    }            public static void main(String[] args) throws Exception {          test01();    }}
dynamicJVM
package com.bdqn.service;public @interface Author {           String name();            int year(); }
Author
package com.bdqn.service;@Author(name="gaoqi", year=2014) public class Emp {        private int empno;    private String ename;        public void sayHello(int a){        System.out.println("sayHello,"+a);    }        public int getEmpno() {        return empno;    }    public void setEmpno(int empno) {        this.empno = empno;    }    public String getEname() {        return ename;    }    public void setEname(String ename) {        this.ename = ename;    }        public Emp(int empno, String ename) {        super();        this.empno = empno;        this.ename = ename;    }        public Emp() {    }}
Emp

 

转载于:https://www.cnblogs.com/ou-pc/p/7710982.html

你可能感兴趣的文章
Android实现静默安装与卸载
查看>>
ef codefirst VS里修改数据表结构后更新到数据库
查看>>
boost 同步定时器
查看>>
[ROS] Chinese MOOC || Chapter-4.4 Action
查看>>
简单的数据库操作
查看>>
解决php -v查看到版本与phpinfo()版本不一致问题
查看>>
iOS-解决iOS8及以上设置applicationIconBadgeNumber报错的问题
查看>>
亡灵序曲-The Dawn
查看>>
Redmine
查看>>
帧的最小长度 CSMA/CD
查看>>
xib文件加载后设置frame无效问题
查看>>
编程算法 - 左旋转字符串 代码(C)
查看>>
IOS解析XML
查看>>
Python3多线程爬取meizitu的图片
查看>>
树状数组及其他特别简单的扩展
查看>>
zookeeper适用场景:分布式锁实现
查看>>
110104_LC-Display(液晶显示屏)
查看>>
httpd_Vhosts文件的配置
查看>>
php学习笔记
查看>>
普通求素数和线性筛素数
查看>>