Class的实例指向方法区中的类本身
获取运行时类的完整结构(父类,所在的包,实现的接口,父类的泛型,所有的方法,所有的属性,构造器,具体的权限修饰符等等)
自定义注解:MyAnnotation
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "hello";
}
自定义接口:MyInterface
public interface MyInterface {
void info();
}
Creature类:
public class Creature<T> implements Serializable{
private char gender;//性别
public double weight;//体重
private void breath(){
System.out.println("生物呼吸");
}
public void eat(){
System.out.println("生物吃东西");
}
}
Person类
@MyAnnotation(value = "hi")
public class Person extends Creature<String> implements Comparable<String>,MyInterface{
private String name;
int age;
public int id;
public Person() {
}
@MyAnnotation(value = "abc")
private Person(String name) {
this.name = name;
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
@MyAnnotation
private String show(String nation){
System.out.println("我的国籍是:"+nation);
return nation;
}
public String display(String interests,int age) throws NullPointerException,ArithmeticException{//这里是强行抛异常,只是为了测试程序
return interests+age;
}
@Override
public int compareTo(String o) {
return 0;
}
@Override
public void info() {
System.out.println("我是一个人");
}
}
反射可以获取具体注解的信息,要想通过反射获取注解,此注解的生命周期要用RUNTIME
这个时候会加载到内存当中,只有在内存中的结构才可以通过反射获取
String value() default “hello”;没有具体的含义
只是来演示基本的功能,注解写好以后就可以在Person的相关结构进行使用
在Person类上进行声明可以加上@MyAnnotation
如果不想用hello,可以重新指定一个值:@MyAnnotation(value = “hi”)写在Person的声明上面
这个东西还可以用来修饰构造器,方法