This code can check whether a class is deprecated or not
@Deprecatedpublic 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?
@DeprecatedStringvariable;
@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.
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.
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.
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.
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?
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With