注解的定义
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD,ElementType.CONSTRUCTOR})
public @interface apple {
String name();
int id() default 0;
Class gid();
}
使用注解的类
import java.util.HashMap;
import java.util.Map;
@apple(name="type",id=1,gid=Long.class)
public class annotationTest {
@apple(name="param",id=1,gid=Long.class) //类成员注解
private int a;
@apple(name="construct",id=2,gid=Long.class)//构造方法注解
public annotationTest(){
}
@apple(name="add",id=1,gid=Long.class)
public void test1(){
}
@apple(name="add",id=1,gid=Long.class)
public void test2(){
}
@apple(name="public method",id=3,gid=Long.class) //类方法注解
public void a(){
Map m = new HashMap(0);
}
@apple(name="protected method",id=4,gid=Long.class) //类方法注解
protected void b(){
Map m = new HashMap(0);
}
@apple(name="private method",id=5,gid=Long.class) //类方法注解
private void c(){
Map m = new HashMap(0);
}
public void b(Integer a){
}
}
测试方法
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;import java.lang.reflect.Method;
public class TestAnnotation {
public TestAnnotation() {
}
public static void main(String[] args) throws ClassNotFoundException {
parseTypeAnnotation();
parseMethodAnnotation();
parseConstructAnnotation();
System.out.println("运行完毕!");
}
public static void parseTypeAnnotation() throws ClassNotFoundException {
//我要获取这个路径annotationTest的类
Class clazz = Class.forName("annotationTest");
//取出里面的注解
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
apple a = (apple)annotation;
System.out.println("1: id="+a.id()+";"+"name="+a.name()+";gid ="+a.gid());
}
}
public static void parseMethodAnnotation(){
//我要获取annotationTest这个类里的所有方法,返回值填到装Method的数组也就是methods里
Method[] methods = annotationTest.class.getDeclaredMethods();
for (Method method : methods) {
//看看这个方法里有没有被apple注解的,有的话给我返回true
boolean hasAnnotation = method.isAnnotationPresent(apple.class);
if (hasAnnotation) {
//既然是有把这些apple注解 给我取出来
apple annotation = method.getAnnotation(apple.class);
System.out.println("2: 方法的名字= " + method.getName()
+ " ;下面就是注解里填的信息了: id = " + annotation.id() + " ;name = "
+ annotation.name() + "; gid= "+annotation.gid());
}
}
}
public static void parseConstructAnnotation(){
//我要获取这个类里面的构造方法,返回值是装构造方法的数组
Constructor[] constructors = annotationTest.class.getConstructors();
for (Constructor constructor : constructors) {
//这个构造方法里有没有这个注解(注解的名字是apple),有的话给我返回true
boolean hasAnnotation = constructor.isAnnotationPresent(apple.class);
if (hasAnnotation) {
//既然是有,那就取出这个apple注解吧,看看他都携带了什么信息吧!
apple annotation =(apple) constructor.getAnnotation(apple.class);
System.out.println("3: 方法的名字= " + constructor.getName()
+ " ;这些就是注解携带的信息了: id = " + annotation.id()+" ;name = "
+ annotation.name() + "; gid= "+annotation.gid());
}
}
}
}