1

I've a Java question about interfaces, annotations and 'inheritance' (let me use this word even if we're talking about interfaces).

Here's an example, then my question:

public interface A {

   @SomeKindOfAnnotation(..)
   boolean modifyElement(String id)
}

public class B implements A{

    @Override
    public boolean modifyElement(String id){

        //Implementation

    }
}

Can the method modifyElement(String id) (in the class B) inherit the annotation @SomeKindOfAnnotation? If yes how can I access the annotation value?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
AlessioG
  • 576
  • 5
  • 13
  • 32

1 Answers1

0

import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)

public @interface SomeKindOfAnnotation{

public String typeOfSecurityNeeded();

}


public interface A {

@SomeKindOfAnnotation(typeOfSecurityNeeded = "low")
public void f3() ;

}

public class B implements A {

@Override
public void f3() {
    // TODO Auto-generated method stub
}

}

import java.lang.reflect.Method;

public class TestProgram {

public static void main(String[] args) {

    try {

        A obj = new B();
        Class c = obj.getClass();
        Method m = c.getMethod("f3");

        if(m.isAnnotationPresent(SomeKindOfAnnotation.class))
        {
            SomeKindOfAnnotation x = m.getAnnotation(SomeKindOfAnnotation.class);
            System.out.println("level of  security is " +x.typeOfSecurityNeeded() );
        }
        else
        {
            System.out.println("no security ");
        }

    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}

}

O/P -------->>>>>>>>>

no security


now add annotation in class B

public class B implements A {

@Override
@SomeKindOfAnnotation(typeOfSecurityNeeded = "low")
public void f3() {
    // TODO Auto-generated method stub

}

}


O/P ---->>>>>

level of security is low

Amaldev
  • 983
  • 8
  • 10