GD Star Rating
loading...
loading...
刚才在写一个方法的时候试图在enum上使用annotation:
- public enum DataKey {
- @Incremental
- @FromProbe
- @Transient(replacePolicy = ReplacePlolicy.REPLACE_IF_LATER_THAN)
- VISIT_COUNT
- }
public enum DataKey {
@Incremental
@FromProbe
@Transient(replacePolicy = ReplacePlolicy.REPLACE_IF_LATER_THAN)
VISIT_COUNT
}然后在merge的时候使用annotation:
- if (key.getClass().isAnnotationPresent(Transient.class)) {
- ...
- }
if (key.getClass().isAnnotationPresent(Transient.class)) {
...
}结果不进if,debug时发现key(DataKey的对象)的类型是DataKey(其实也挺顺理成章的),于是使用如下代码:
- if (DataKey.class.getField(key.name()).isAnnotationPresent(Transient.class)) {
- ...
- }
if (DataKey.class.getField(key.name()).isAnnotationPresent(Transient.class)) {
...
}结果正确。
结论:在对enum类型使用FIELD一级annotation时需要使用第二种方法进行反射
原创内容,转载请注明: 转载自拈花微笑
本文链接地址: 如何在Java的enum中使用annotation

2 Comments
loading...
嗯,嗯, 这个好理解, enum也是类, 在这个类里面有自己的实例
loading...
许久不见技术贴 = =