定义:加载完类之后,在堆内存的方法区中就产生一个Class类型的对象(注意和关键字class的区别,class是我们平时定义类用的,Class可以说是表示类的类),一个类只有一个Class对象,这个对象就包含有类的结构信息,我们就可以通过这个对象获得类的结构信息。这个对象就像一面镜子,我们可以通过这个镜子看到类的结构,所以,我们形象的称之为:反射
作用:反射在调用类的私有方法、私有属性,获取注解方面的用处很大
举例:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class test1 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//第一步,获取类的Class对象,有三种方式
//方式一:知道类的路径
Class c = Class.forName("reflection.Student");
// //方式二:知道类名
// Class c1=Student.class;
// //方式三:知道对象
// Student student = new Student();
// Class c2=student.getClass();
//第二步,构建Student对象,有两种方式
//方式一:需要Student类有无参构造函数,否则报错
Student student= (Student) c.newInstance();
System.out.println(student);
// //方式二:通过有参构造函数
// Constructor constructor = c.getDeclaredConstructor(String.class, int.class);
// Student student = (Student) constructor.newInstance("lisi",1);
//调用私有普通方法
Method method = c.getDeclaredMethod("setName", String.class);
method.setAccessible(true);//关闭检测,才能访问私有的;而且能提高效率
method.invoke(student, "wanglx");//对象+参数
//设置私有属性,Person里面就算没有setAge方法,照样可以通过反射修改它的属性
Field age = c.getDeclaredField("age");
age.setAccessible(true);
age.set(student,18);//注意属性用的是set,方法用的是invoke
System.out.println(student);
//反射获取注解
//获取类的注解,先获取类,再通过类获取注解
TableAno tableAno = (TableAno) c.getAnnotation(TableAno.class);
String value=tableAno.value();
System.out.println(value);
//获取属性的注解,先获取属性,再通过属性获取注解
Field name = c.getDeclaredField("name");
FieldAno fieldAno = (FieldAno) name.getAnnotation(FieldAno.class);
String colunmName=fieldAno.colunmName();
String type=fieldAno.type();
int length=fieldAno.length();
System.out.println(colunmName+" "+type+" "+length);
}
}
@TableAno("db_student")
class Student {
@FieldAno(colunmName = "db_name",type = "String",length = 3)
private String name;
@FieldAno(colunmName = "db_age",type = "int",length =2)
private int age;
public Student() {
}
public Student( String name ,int age) {
this.name = name;
this.age = age;
}
private void setName(String name) {
this.name=name;
}
public void go() {
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//类名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableAno {
String value();
}
//属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAno {
String colunmName();
String type();
int length();
}