zoukankan      html  css  js  c++  java
  • 动态给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)); } }

      

  • 相关阅读:
    MS CRM 2011 RC中的新特性(4)——活动方面之批量编辑、自定义活动
    最近的一些有关MS CRM 2011的更新
    MS CRM 2011 RC中的新特性(6)——连接
    MS CRM 2011 RC中的新特性(7)—仪表板
    参加MS CRM2011深度培训课程——第一天
    MS CRM 2011插件调试工具
    MS CRM2011实体介绍(四)——目标管理方面的实体
    MS CRM 2011 RC中的新特性(3)——客户服务管理方面
    MS CRM 2011 RC中的新特性(8)—数据管理
    ExtAspNet 登陆
  • 原文地址:https://www.cnblogs.com/albertXe/p/14523539.html
Copyright © 2011-2022 走看看