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)); } }

      

  • 相关阅读:
    PHP用户注册邮箱验证激活帐号
    利用openssl进行RSA加密解密
    RSA算法使用介绍
    JS七种加密解密方法
    JS调用PHP 和 PHP调用JS的方法举例
    php注册登录时生成的验证码
    Joomla!网站扫描工具joomscan
    Xamarin XAML语言教程控件模板的模板绑定
    Xamarin.Forms使用Slider注意问题
    ASP.net 资源请求漏洞利用工具PadBuster
  • 原文地址:https://www.cnblogs.com/albertXe/p/14523539.html
Copyright © 2011-2022 走看看