注解的实现:
package JavaCore;
import java.lang.annotation.*;
//@MyAnnotation 报错
public class Innocation {
public static void main(String[] args) {
}
@MyAnnotation(name = "人")
public void test(){
}
}
//元注解
@Target(value = ElementType.METHOD)//Target表示能够作用在哪里
@Retention(value = RetentionPolicy.RUNTIME) //运行时有效
@Documented //是否将注解生成在JAVAdoc中
@Inherited //子类可以继承父类的注解
@interface MyAnnotation{
//注解的参数:参数类型+参数名();
String name() default "";
int id() default -1;
String[] str() default {"s1","s2"};
}
反射操作注解;
package JavaCore;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Innocation {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class stu = Class.forName("JavaCore.Student");
//获得类上的注解
MyAnnotation annotation = (MyAnnotation) stu.getAnnotation(MyAnnotation.class);
System.out.println(annotation.value());
//我是类上的注解
//获得成员变量上的注解
Field name = stu.getDeclaredField("name");
MyName myName = name.getAnnotation(MyName.class);
System.out.println(myName.name());
//小明
}
}
@MyAnnotation("我是类上的注解")
class Student{
@MyName(name = "小明")
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation{
String value();
}
@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyName{
String name();
}