Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;

like image 740
Hernán Eche Avatar asked Jul 26 '17 13:07

Hernán Eche


People also ask

Which annotation is used to indicate that the marked element is deprecated?

@Deprecated @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation.

How annotations are obtained at runtime by use of reflection?

If annotations specify a retention policy of RUNTIME, then they can be queried at run time by any Java program through the use of reflection. Reflection is the feature that enables information about a class to be obtained at run time.

How do you use deprecated annotations?

Using the @Deprecated Annotation To use it, you simply precede the class, method, or member declaration with "@Deprecated." Using the @Deprecated annotation to deprecate a class, method, or field ensures that all compilers will issue warnings when code uses that program element.

Which of the following is a deprecated method in Java?

The @Deprecated annotation tells the compiler that a method, class, or field is deprecated and that it should generate a warning if someone tries to use it. That's what a deprecated class or method is. It's no longer relevant.


1 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?
like image 145
HTNW Avatar answered Oct 24 '22 04:10

HTNW