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



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


@Deprecatedpublic 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);             
}  
}

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


@DeprecatedStringvariable;

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?

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

最新更新