lundi 6 mai 2019

In Java, how does one programmatically determine whether an `@Override` annotation is present in source code?

How does one programmatically determine whether an @Override annotation is present in Java source code? I have tried using method isAnnotationPresent.

public class A
  {
  int a = 1 ;
  @Override
  public String toString()
    { return "attribute a = " + a ; }
  }

public class B extends A
  {
  int b = 2 ;
  @Override
  public String toString ()
    { return super.toString() + ", " + "attribute b = " + b ; }
  }

import java.lang.reflect.Method ;
import java.lang.annotation.Annotation ;
public class Main
  {
  public static void main ( String [] args )
    {
    A a = new A() ;
    B b = new B() ;
    System.out.println ( a.toString() ) ;
    System.out.println ( b.toString() ) ;

    Class c = b.getClass() ;
    Method m = null ;
    try
      { m = c.getMethod("toString") ; }
    catch ( Exception e )
      { System.exit(0) ; }
    System.out.println ( "b's toString method is " + m ) ;    

    boolean bOverrides = m.isAnnotationPresent(Override.class) ;
    System.out.println ( "bOverrides = " + bOverrides ) ;
    }
  }

Of course, the @Override annotation within the source code of class B could be omitted, and I'd like to know whether that annotation is, indeed, present in the Java source code or absent. Note that the output of main is:

bOverrides = false





Aucun commentaire:

Enregistrer un commentaire