Hernán Eche
Hernán Eche

Reputation: 6898

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;

Upvotes: 7

Views: 3224

Answers (2)

HTNW
HTNW

Reputation: 29193

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?

Upvotes: 7

lance-java
lance-java

Reputation: 27996

You are checking the Class annotations. The reflection API's also give you access to Field and Method annotations.

See

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

A couple of problems with your implementation

  1. You are only checking getAnnotations[0] when there might be more than one annotation
  2. You are testing toString().contains("Deprecated") when you should check .equals(Deprecated.class)
  3. You could use .getAnnotation(Deprecated.class)

Upvotes: 2

Related Questions