java 8中的注解,更改Java的8场注解注释值

I think title describes the problem. Here's some code:

import static org.junit.Assert.assertEquals;

import java.lang.annotation.*;

public class Main {

public static void main(String[] args) throws Exception {

assertEquals("foo", Main.class.getDeclaredMethod("myMethod").getAnnotation(Anno.class).param());

// the magic here -> set to bar

assertEquals("bar", Main.class.getDeclaredMethod("myMethod").getAnnotation(Anno.class).param());

}

@Anno(param = "foo")

public void myMethod() {}

@Retention(RetentionPolicy.RUNTIME)

@interface Anno {

String param();

}

}

So far I'm guessing this is not possible. It seems that always when you try to get a method via reflection you only get copies and all values (like annotations) are reread from a deeper java layer. In these copies you could change values but these are gone if you reload.

Is there something I missed or is it really not possible?

解决方案

Annotations are modifiers just like private or synchronized. They are part of the invariant static structure of a class and not intended to be modified. You can hack into the Reflection implementation to make a particular method print what you want, but besides the dirtiness of the hack, you simply haven’t changed the annotation, you just hacked a data structure of a particular library.

There are other Reflection or byte code manipulation libraries which won’t use the built-in Reflection API but read the byte code directly (e.g. via getResource() or via the Instrumentation API). These libraries will never notice your manipulation.

Note further, since these values are supposed to be constants embedded in the class file, a Reflection implementation could always use lazy fetching plus dropping of the cached values depending on uncontrollable conditions as these values can always be refetched. There’s also no guaranty that the Reflection implementation uses data structures at all; it could also generate code returning the constant values.

In other words, if you want to associate mutable data with a method, don’t use annotations. You could simple use a Map, or, if you just have that one particular method, declare a good old static field which already provides all the features you need and is much easier to handle.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值