导入 java.lang.annotation.Retention;导入 java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
公共@interface SomeKindOfAnnotation{
public String typeOfSecurityNeeded();
}
公共接口 A {
@SomeKindOfAnnotation(typeOfSecurityNeeded = "low")
public void f3() ;
}
公共类 B 实现 A {
@Override
public void f3() {
// TODO Auto-generated method stub
}
}
导入java.lang.reflect.Method;
公共类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 -------->>>>>>>>>
没有安全感
现在在 B 类中添加注释
公共类 B 实现 A {
@Override
@SomeKindOfAnnotation(typeOfSecurityNeeded = "low")
public void f3() {
// TODO Auto-generated method stub
}
}
输出 ---->>>>
安全级别低