【问题标题】:How to determine (at runtime) if a variable is annotated as deprecated?如何确定(在运行时)变量是否被注释为已弃用?
【发布时间】:2017-07-26 13:45:25
【问题描述】:

这段代码可以检查一个是否被弃用

@Deprecated
public classRetentionPolicyExample{

             public static void main(String[] args){  
                 boolean isDeprecated=false;             
                 if(RetentionPolicyExample.class.getAnnotations().length>0){  
                     isDeprecated= RetentionPolicyExample.class  
                                   .getAnnotations()[0].toString()
                                   .contains("Deprecated");  
                 }  
                 System.out.println("is deprecated:"+ isDeprecated);             
             }  
      }

但是,如何检查是否有变量被注释为已弃用?

@Deprecated
Stringvariable;

【问题讨论】:

  • 小心.getAnnotations()[0],因为一个类可能有多个注释
  • @Hernán,你有一个类,你想检查它是否至少有一个字段,标记为@Deprecated?
  • 检索类的字段 - 然后使用Field::getAnnotations?
  • @VadymPechenoha 我在想具体的变量检查,但你说的可以检查每个字段,也可以
  • @assylias 谢谢,现在测试 Field 类,如答案中所示

标签: java reflection annotations deprecated


【解决方案1】:
import java.util.stream.Stream;

Field[] fields = RetentionPolicyExample.class // Get the class
                .getDeclaredFields(); // Get its fields

boolean isAnyDeprecated = Stream.of(fields) // Iterate over fields
                // If it is deprecated, this gets the annotation.
                // Else, null
                .map(field -> field.getAnnotation(Deprecated.class))
                .anyMatch(x -> x != null); // Is there a deprecated annotation somewhere?

【讨论】:

  • 它对我来说很好用。更改 @Deprecated 注释后是否重新编译了该类?当您测试 false 时,您是否确保 no 字段为 @Deprecated
【解决方案2】:

您正在检查Class 注释。反射 API 还允许您访问 FieldMethod 注释。

  • Class.getFields() 和 Class.getDeclaredFields()
  • Class.getMethods() 和 Class.getDeclaredMethods()
  • Class.getSuperClass()

您的实施存在一些问题

  1. 只有在可能有多个注释时才检查getAnnotations[0]
  2. 您正在测试toString().contains("Deprecated"),此时您应该检查.equals(Deprecated.class)
  3. 你可以使用.getAnnotation(Deprecated.class)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多