gpt4 book ai didi

jaxb - javassist 不在现有字段中注入(inject)注释

转载 作者:行者123 更新时间:2023-12-01 05:45:26 25 4
gpt4 key购买 nike

我正在尝试使用 Javassist 在运行时注入(inject) JAXB 注释。我写了以下代码:

public class AssistAnnotationInjector {
public static void addAnnotationRunTime(String className, String fieldName) throws NotFoundException, CannotCompileException, IOException, ClassNotFoundException{

CtClass ctClass = ClassPool.getDefault().get(className);
ClassFile ccFile = ctClass.getClassFile();
ConstPool constPool = ccFile.getConstPool();
AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
Annotation annot = new Annotation("javax.xml.bind.annotation.XmlTransient",constPool);
attr.addAnnotation(annot);
CtField field = ctClass.getDeclaredField(fieldName);
field.getFieldInfo().addAttribute(attr);
System.out.println(field.getAnnotation(XmlTransient.class));
ccFile.setVersionToJava5();
ctClass.writeFile();
}

public static void main (String args[]) throws CannotCompileException, NotFoundException, IOException, SecurityException, NoSuchMethodException, ClassNotFoundException, JAXBException, NoSuchFieldException{
Person<Student> p = new Person<Student>();
p.setName("XYZ");
Student s = new Student();
s.setName("ABC");
s.setId("239423");
p.setPayload(s);

addAnnotationRunTime("RuntimeAnnotation.Person", "name");

Field f = p.getClass().getDeclaredField("name");
System.out.println(f.getAnnotation(XmlTransient.class));

JAXBContext context = JAXBContext.newInstance(p.getClass());

Marshaller mr = context.createMarshaller();
mr.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

mr.marshal(p, System.out);
}
}

Person.java 类是:

@XmlRootElement(name="Person")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({Student.class})
public class Person <T>{

private T payload;

private String name;

public void setPayload(T payload){
this.payload = payload;
}

public T getPayload(){
return payload;
}

public void setName(String name){
this.name = name;
}

public String getName(){
return name;
}
}

在 AssistAnnotationInjector.java 中,我试图将 XmlTransient 注释添加到“名称”字段。但是名称字段仍在编码输出中。为什么会这样?

PS:编码输出是:

@javax.xml.bind.annotation.XmlTransient
null
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Person>
<payload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="student">
<name>ABC</name>
<id>239423</id>
</payload>
**<name>XYZ</name>**
</Person>

名称标签不应出现在输出中..

最佳答案

您基本上有 2 个选择:

  1. 在加载类之前进行修改。您不能以正常方式使用反射!可以尝试将 org.reflections 与 Maven 插件一起使用来预取类。参见 here了解更多信息。

  2. 使用自定义类加载器加载修改后的类。参见 here了解更多信息。

关于jaxb - javassist 不在现有字段中注入(inject)注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15332399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com