import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method;@Retention(RetentionPolicy.RUNTIME)@interface MySingle { int value(); // this variable name must be value}
注意:在自定义注释时候,想让java反射机制,得到注释,则,在定义注释时候,一定要加上@Retention(RetentionPolicy.RUNTIME)并且,所有的注释,都是Annotation的子类,class Single { @MySingle(100) public static void myMeth() { Single ob = new Single(); try { Method m = ob.getClass().getMethod("myMeth"); MySingle anno = m.getAnnotation(MySingle.class); System.out.println(anno.value()); // displays 100 } catch (NoSuchMethodException exc) { System.out.println("Method Not Found."); } } public static void main(String args[]) { myMeth(); }}
转载请注明原文地址: https://ibbs.8miu.com/read-2261041.html