Javassist修改已有类加新的属性注解
Posted HiveDark
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javassist修改已有类加新的属性注解相关的知识,希望对你有一定的参考价值。
一、新建类PersonService
name
字段目前是有两个注解Autowired和JsonFormat。
package com.david.test.test_springboot_schema.javassist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.fasterxml.jackson.annotation.JsonFormat;
@Controller
public class PersonService
@Autowired
@JsonFormat
private String name;
public void getPerson()
System.out.println("get Person");
public void personFly()
System.out.println("oh my god,I can fly");
二、javassist动态修改name属性,增加注解
在原有基础上新增JsonIgnore注解,注意AnnotationsAttribute的获取方式,应先检测是否已经存在,存在则用已有的AnnotationsAttribute,否则新增的会覆盖原有的注解
。
private static void testAnnotation2() throws Exception
// TODO Auto-generated method stub
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.get("com.david.test.test_springboot_schema.javassist.PersonService");
//字段添加注解
CtField ctField = ctClass.getDeclaredField("name");
List<AttributeInfo> attributeInfos = ctField.getFieldInfo().getAttributes();
AnnotationsAttribute annotationsAttribute = !attributeInfos.isEmpty()?(AnnotationsAttribute) attributeInfos.get(0):
new AnnotationsAttribute(ctField.getFieldInfo().getConstPool(), AnnotationsAttribute.visibleTag);
Annotation annotation = new Annotation("com.fasterxml.jackson.annotation.JsonIgnore", ctField.getFieldInfo().getConstPool());
annotationsAttribute.addAnnotation(annotation);
ctField.getFieldInfo().addAttribute(annotationsAttribute);
ctClass.writeFile("D:\\\\javassist\\\\");
//class
System.out.println("==================TEST=================");
Class<?> afterClass = ctClass.toClass();
Field field = afterClass.getDeclaredField("name");
java.lang.annotation.Annotation[] annotation2 = field.getAnnotations();
for(java.lang.annotation.Annotation annotation3:annotation2)
System.out.println(annotation3);
ctClass.detach();
三、运行结果
以上是关于Javassist修改已有类加新的属性注解的主要内容,如果未能解决你的问题,请参考以下文章