如何在Java的enum中使用annotation

GD Star Rating
loading...

刚才在写一个方法的时候试图在enum上使用annotation:

  1. public enum DataKey {
  2.     @Incremental
  3.     @FromProbe
  4.     @Transient(replacePolicy = ReplacePlolicy.REPLACE_IF_LATER_THAN)
  5.     VISIT_COUNT
  6. }
public enum DataKey {
    @Incremental
    @FromProbe
    @Transient(replacePolicy = ReplacePlolicy.REPLACE_IF_LATER_THAN)
    VISIT_COUNT
}

然后在merge的时候使用annotation:

  1. if (key.getClass().isAnnotationPresent(Transient.class)) {
  2.     ...
  3. }
if (key.getClass().isAnnotationPresent(Transient.class)) {
    ...
}

结果不进if,debug时发现key(DataKey的对象)的类型是DataKey(其实也挺顺理成章的),于是使用如下代码:

  1. if (DataKey.class.getField(key.name()).isAnnotationPresent(Transient.class)) {
  2.     ...
  3. }
if (DataKey.class.getField(key.name()).isAnnotationPresent(Transient.class)) {
    ...
}

结果正确。
结论:在对enum类型使用FIELD一级annotation时需要使用第二种方法进行反射

原创内容,转载请注明: 转载自拈花微笑

本文链接地址: 如何在Java的enum中使用annotation

685

2 Comments

  • YuncaI
    2008 年 10 月 10 日 - 上午 12:03 | Permalink
    GD Star Rating
    loading...

    嗯,嗯, 这个好理解, enum也是类, 在这个类里面有自己的实例

  • Js
    2008 年 09 月 23 日 - 上午 12:07 | Permalink
    GD Star Rating
    loading...

    许久不见技术贴 = =

  • 发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注

    *

    您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">

    :wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!:

    使用新浪微博登陆

    无觅相关文章插件,快速提升流量