JAVA之注解(代码)

来源:互联网 发布:营销型企业网站源码 编辑:程序博客网 时间:2024/06/08 16:36
package cn.com.annotation;
/**
 * 自定义的一个注解
 */
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;


@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String hello() default "哈哈哈";
String hi();

}



package cn.com.annotation;
/**
 * 使用注解
 */


@MyAnnotation(hi = "嗨")
public class MyTest {
@MyAnnotation(hi = "haha")
@Deprecated
public void output() {
System.out.println("打印");
}
}



package cn.com.annotation;


/**
 * 通过反射测试注解
 */
import java.lang.reflect.Method;


public class MyReflection {

public static void main(String[] args) throws Exception {
MyTest test = new MyTest();
Class<MyTest> classType = MyTest.class;

Method method = classType.getMethod("output", new Class[]{});

if(method.isAnnotationPresent(MyAnnotation.class)) {
method.invoke(test, new Object[]{});
MyAnnotation my = method.getAnnotation(MyAnnotation.class);
String hi = my.hi();
String hello = my.hello();
System.out.println(hi + ", " + hello);
}
}
}

原创粉丝点击