Her*_*che 5 java reflection annotations deprecated
此代码可以检查是否已弃用类
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如何检查是否有任何变量注释为已弃用?
@Deprecated
Stringvariable;
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?
Run Code Online (Sandbox Code Playgroud)