此代码可以检查类是否已弃用
@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;
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 还允许您访问Field
和Method
注释。
看
- Class.getFields(( 和 Class.getDeclaredFields((
- Class.getMethods(( 和 Class.getDeclaredMethods((
- Class.getSuperClass((
您的实现存在几个问题
- 您仅在可能有多个注释时检查
getAnnotations[0]
- 您正在测试
toString().contains("Deprecated")
何时应检查.equals(Deprecated.class)
- 您可以使用
.getAnnotation(Deprecated.class)