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

Hernán Eche :

This code can check whether a class is deprecated or not

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

But, how can be checked if any variable is annotated as deprecated?

@Deprecated
Stringvariable;

HTNW :
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?

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465606&siteId=1