此代码可以检查是否已弃用类
@Deprecated
public class
RetentionPolicyExample
{
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
String
的 variable;
答案 0 :(得分:5)
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?
答案 1 :(得分:2)
您正在查看Class
注释。通过反射API,您还可以访问Field
和Method
注释。
见
您的实施存在一些问题
getAnnotations[0]
toString().contains("Deprecated")
.equals(Deprecated.class)
.getAnnotation(Deprecated.class)