1、自定义注解1
package cn.com.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
}
2、自定义注解2,有一个默认的值为0
package cn.com.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
public int hello() default 0;
}
3、测试注解
package cn.com.annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyAnotationTest {
public static void main(String[] args) {
Test t=new Test();
//使用遍历的方式获取
/*Annotation[] an= t.getClass().getAnnotations();
for(Annotation a:an)
{
System.out.println(a.annotationType().getName());
}*/
//如果类的注解存在
if(t.getClass().isAnnotationPresent(MyAnnotation1.class))
{
MyAnnotation1 my1=t.getClass().getAnnotation(MyAnnotation1.class);
System.out.println(my1.annotationType().getName());
System.out.println("你得到了类的注解");
}
try {
Method method1=t.getClass().getMethod("test1", new Class[]{});
Method method2=t.getClass().getMethod("test2", new Class[]{});
Method method3=t.getClass().getMethod("test3", new Class[]{});
try {
//方法的调用
method1.invoke(t, null);
System.out.println(method1.getModifiers());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果方法的注解存在
if(method1.isAnnotationPresent(MyAnnotation1.class))
{
MyAnnotation1 my1=method1.getAnnotation(MyAnnotation1.class);
System.out.println(my1.annotationType().getName());
System.out.println("你得到了方法test1上的MyAnnotation1注解");
}
if(method2.isAnnotationPresent(MyAnnotation2.class))
{
MyAnnotation2 my2=method2.getAnnotation(MyAnnotation2.class);
System.out.println(my2.hello());//得到注解默认值
System.out.println("你得到了方法test2上的MyAnnotation2注解");
}
if(method3.isAnnotationPresent(MyAnnotation2.class))
{
MyAnnotation2 my3=method3.getAnnotation(MyAnnotation2.class);
System.out.println(my3.hello());//得到赋予的值
System.out.println("你得到了方法test3上的MyAnnotation2注解");
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
@MyAnnotation1
class Test {
@MyAnnotation1
public void test1() {
System.out.println("你使用了MyAnnotation1");
}
@MyAnnotation2
public void test2() {
System.out.println("你使用了MyAnnotation2默认值");
}
@MyAnnotation2(hello=3)
public void test3() {
System.out.println("你使用了MyAnnotation2并为其赋值");
}
}