简体   繁体   English

更改注释方法的返回类型

[英]Change the return type of annotation method

given the following custom annotation 给定以下自定义注释

 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.FIELD)
 public @interface TGT {
  String age();
}

and somewhere in a class code it is used for a field as : 在类代码中的某个地方,它用于字段:

  @TGT(age="someValue")
  private String someID;

Is it possible to change the return value of someID's method age() from "someValue": to so something else or in other words other String value?So when someone gets someID's annotation via reflection and then invokes the age() method of the annotation to get different value? 是否有可能将someID的age()方法的返回值从“ someValue”:更改为其他值或换句话说为其他String值?所以,当有人通过反射获取someID的注释,然后调用注释的age()方法时获得不同的价值?

Yes, it is possible but not with pure reflection. 是的,这是可能的,但不能完全反射。 If you want to change the object without replacing it by another object you'll have to use a bytecode manipulation lib like ASM (see how it is done in Lombok ). 如果要更改对象而不用其他对象替换,则必须使用字节码操作库(如ASM)(请参阅Lombok中的操作 )。 But this way would be very complex. 但是这种方式将非常复杂。

In case if you are allowed to replace an abject by a proxy it would even be possible with pure reflection + aspects engine (se how Spring does it with help of CGLIB ). 如果允许您使用代理替换对象,则甚至可以使用纯反射+方面引擎(例如Spring如何在CGLIB的帮助下完成 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM