javassit创建一个类实现某个接口

引入依赖

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.25.0-GA</version>
</dependency>

要实现的接口

public interface IHandler {

    void handle(String str);
}

代理类中使用的属性

public class User {
    public String name;
}

代理实现

package com.javassit;

import javassist.*;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ConstPool;
import javassist.bytecode.FieldInfo;

/**
 * @Author wenbin.xu
 * @Date 2022/9/9 9:25
 */
public class Proxy {

    public static void main(String[] args) throws NotFoundException, CannotCompileException, IllegalAccessException, InstantiationException {
        ClassPool pool = ClassPool.getDefault();
        //创建代理类对象
        CtClass ctClass = pool.makeClass("handlerImpl");
        //设置代理类的接口
        CtClass interj = pool.getCtClass("com.javassit.IHandler");
        CtClass[] interfaces = new CtClass[]{interj};
        ctClass.setInterfaces(interfaces);
        // 获取常量池
        ConstPool constPool = ctClass.getClassFile().getConstPool();
        // 创建属性,调用远程服务使用
        CtField ctField  = new CtField(pool.get("com.javassit.User"), "user", ctClass);
        ctField.setModifiers(AccessFlag.PUBLIC);
        // 添加Autowired注解,后续注册到spring中会自动装配
        /*FieldInfo fieldInfo = ctField.getFieldInfo();
        AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
        Annotation filedAnnotation = new Annotation(Autowired.class.getName(), constPool);
        annotationsAttribute.addAnnotation(filedAnnotation);
        fieldInfo.addAttribute(annotationsAttribute);*/
        // 加入到类文件中
        ctClass.addField(ctField);

        //代理类的所有方法
        CtMethod[] methods = interj.getDeclaredMethods();

        for(CtMethod method : methods) {
            // 创建代理类的方法
            String methodName = method.getName();
            CtMethod cm = new CtMethod(method.getReturnType(), methodName, method.getParameterTypes(), ctClass);
            // 使用方法中的参数 $1 $2 ...
            cm.setBody("{user = new com.javassit.User(); user.name = $1; return user;}");
            ctClass.addMethod(cm);
        }
        Class<?> aClass = ctClass.toClass();
        IHandler instance = (IHandler)aClass.newInstance();
        User user = instance.handle("xwb");
        System.out.println(user.name);
    }
}

运行结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值