【问题标题】:Java annotation dynamic typecastJava注解动态类型转换
【发布时间】:2011-04-29 13:08:21
【问题描述】:

我有 2 种 java 注释类型,比如说 XA 和 YA。两者都有一些方法()。我解析源代码并检索 Annotation 对象。现在我想动态地将注释转换为它的真实类型,以便能够调用方法()。如果没有instanceof 语句,我该怎么做?我真的很想避免类似开关的来源。我需要这样的东西:

Annotation annotation = getAnnotation(); // I recieve the Annotation object here
String annotationType = annotation.annotationType().getName();

?_? myAnnotation = (Class.forName(annotationType)) annotation;
annotation.method(); // this is what I need, get the method() called

?_?意味着我不知道 myAnnotation 类型是什么。我不能将基类用于我的 XA 和 YA 注释,因为不允许在注释中继承。还是有可能以某种方式做到?

感谢您的任何建议或帮助。

【问题讨论】:

    标签: java casting annotations dynamic-typing


    【解决方案1】:

    你为什么不使用类型安全的方式来检索你的注解?

    final YourAnnotationType annotation = classType.getAnnotation(YourAnnotationType.class);
    annotation.yourMethod();
    

    如果找不到您的注释,则返回 null。

    请注意,这也适用于字段和方法。

    【讨论】:

    • 这并不能解决我的问题。我需要为我使用的每个 MyAnnotationType 声明这一行。 classType.getAnnotation(YourAnnotationType.class);所以它看起来又像 switch。
    【解决方案2】:

    一种方法是使用它的名称动态调用该方法:

    Annotation annotation = getAnnotation();
    Class<? extends Annotation> annotationType = annotation.annotationType();
    Object result = annotationType.getMethod("method").invoke(annotation);
    

    这种方法风险很大,如果需要,完全会影响代码重构。

    【讨论】:

    • 效果很好!我从@Table 注释中获取名称属性的方法是使用一些简单的正则表达式从annotation.toSring() 中提取表名,但您的解决方案更优雅。
    猜你喜欢
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 2011-08-17
    • 1970-01-01
    相关资源
    最近更新 更多