- 一:注解
- 二:反射
自定义注解:
import java.lang.annotation.*;
@MyAnnotation(value = "自定义注解")
public class Annotation {
// 注解如果参数没有默认值,则必须给注解赋值
@MyAnnotation(value = "qq")
public void s(){
}
}
@Target(value = {ElementType.TYPE,ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation {
// 注解的参数:参数类型 参数名();
String value();
String name() default "my name is liu ming yong";
int age() default 0;
String[] schools() default {"国防大学","清华大学"};
}
二:反射
反射概念:
Reflection(反射)是java被视为准动态语言(在运行期间可改变结构的语言)的关键,反射允许程序在执行期间获取到任何类的内部信息,并可直接操作任意对象的内部属性或方法。
类加载完成后,在堆内存方法区中就产生了一个Class类型对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。
获得反射Class的几种方式:
public class Reflection01 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();
// 方式一:通过对象获得
Class c1 = person.getClass();
System.out.println(c1);
// 方式二:通过forName获得
Class c2 = Class.forName("注解与反射.Student");
System.out.println(c2);
// 方式三:通过类名.class获得
Class c3 = Student.class;
System.out.println(c3);
// 方式四:通过基本数据类型的包装类获取
Class c4 = Integer.TYPE;
System.out.println(c4);
// 获取父类类型
Class c5 = c1.getSuperclass();
System.out.println(c5);
}
}
class Person {
String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + ''' +
'}';
}
}
class Student extends Person {
}
获取类运行时的结构:



