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

This code can check if the class is deprecated or not.

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

But how can one check if a variable is annotated as deprecated?

@Deprecated
String variable;

+4
source share
2 answers
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?
+5
source

You check annotations Class. The reflection API also gives you access to Fieldand annotations Method.

Cm

  • Class.getFields () and Class.getDeclaredFields ()
  • Class.getMethods () and Class.getDeclaredMethods ()
  • Class.getSuperClass ()

A couple of problems with your implementation

  • getAnnotations[0],
  • toString().contains("Deprecated"), .equals(Deprecated.class)
  • .getAnnotation(Deprecated.class)
+2

Source: https://habr.com/ru/post/1682321/


All Articles