• 动态给class加注解



    package vine.common; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.AttributeInfo; import javassist.bytecode.annotation.Annotation; import javassist.bytecode.annotation.IntegerMemberValue; import lombok.SneakyThrows; import java.lang.reflect.Field; import java.util.List; public class AssistUtil { @SneakyThrows public static Class<?> addAnnotation(String clzName,String annotationName) { ClassPool classPool = ClassPool.getDefault(); CtClass clz = classPool.get(clzName); CtField[] fields = clz.getDeclaredFields(); int i = 0; for (CtField field : fields) { List<AttributeInfo> attributes = field.getFieldInfo().getAttributes(); AnnotationsAttribute annotationsAttribute; if (!attributes.isEmpty()) { annotationsAttribute = (AnnotationsAttribute) attributes.get(0); }else { annotationsAttribute = new AnnotationsAttribute(field.getFieldInfo().getConstPool(), AnnotationsAttribute.visibleTag); } Annotation annotation = new Annotation(annotationName, field.getFieldInfo().getConstPool()); annotation.addMemberValue("ordinal",new IntegerMemberValue(field.getFieldInfo().getConstPool(),i++)); // annotation.addMemberValue("ordinal",new IntegerMemberValue(i++,field.getFieldInfo().getConstPool())); annotationsAttribute.addAnnotation(annotation); field.getFieldInfo().addAttribute(annotationsAttribute); } Class<?> afterClass = clz.toClass(); for (Field field : afterClass.getDeclaredFields()) { for (java.lang.annotation.Annotation annotation : field.getAnnotations()) { System.out.println(annotation); } } return afterClass; } @SneakyThrows public static String toJsonString(Class<?> type) { SerializerFeature[] serializer = {SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse}; Object o = type.newInstance(); return JSONObject.toJSONString(o,serializer); } public static void main(String[] args) { Class<?> aClass = addAnnotation("vine.base.Prepare", "com.alibaba.fastjson.annotation.JSONField"); System.out.println(toJsonString(aClass)); } }

      

  • 相关阅读:
    YZR.Data 事务处理(Tranaction)
    啊Ran讲微信开发(.net) :公众号(服务号)+自定义服务器(OAuth授权登录)
    啊Ran讲微信开发(.net) 目录结构
    啊Ran讲微信开发(.net) :公众号(订阅号)+自定义服务器(自定义菜单)
    js和jQuery的总结
    Javascript重要解析
    IntelliJ-项目配置,解决no artifacts的warnings
    农夫过河问题(java版)
    redis安装常见问题
    idea 项目中 maven 编译出错Fatal error compiling: 无效的目标发行版: 1.8 -> [Help 1] 解决方法
  • 原文地址:https://www.cnblogs.com/albertXe/p/14523539.html
Copyright © 2020-2023  润新知