如何确定(在运行时)变量是否被注释为已弃用?

How to determine (at runtime) if a variable is annotated as deprecated?

此代码可以检查 class 是否已弃用

@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;

您正在检查 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)
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?