反射
一、类对象
- 概念:所有的类都存在一个类对象,这个对象用于提供类本身的信息,如构造方法、成员变量等。
- 类对象是用于描述类有什么属性、方法的
- demo由Cat类演示:
public class Cat {
public int length,weight;
public static String name;
static{
name="Tom";
}
public Cat() {
}
public Cat(int l,int w) {
length=l;
weight=w;
}
public String toString() {
return "length:"+length+" weight:"+weight;
}
public void setLength(int length) {
this.length=length;
}
}
二、获取类对象
- 获取Cat类对象有三种方法:
- 方法1:Class.forName(String classname);
- 方法2:Cat.class;
- 方法3:new Cat().getClass();
public class ReactDemo {
public static void main(String[] args) throws ClassNotFoundException {
String classname="demo.Cat";
Class first=Class.forName(classname);
Class second=Cat.class;
Class third=new Cat().getClass();
}
}
- 获取类对象时,会导致静态对象被初始化(只会初始化一次);
String classname="demo.Cat";//包名.类名
Class first=Class.forName(classname);
System.out.println(Cat.name);
String classname="demo.Cat";
Class first=Class.forName(classname);
Constructor c=first.getConstructor();
Cat tom=(Cat)c.newInstance();
三、访问属性与方法
- 访问属性
- 对与private属性需要setAccessible才可以访问,也可以通过setter、getter访问,主要使用后者,不会破坏封装性
- Field
- getField()方法:获取public的字段,包括从父类继承的
- getDeclraedField()方法:可以获取全部字段 ,但是不包括从父类继承的。注意:获取字段不代表可以访问,仍然是只能访问setAccessible(true)才可以
- getFields()/getDeclaredFields():获取多个,返回数组
Cat tom=new Cat(30,9);
Class c=tom.getClass();
Field f1=c.getDeclaredField("weight");
f1.set(tom, 10);
System.out.println(tom.toString());
- Method
- getMethod()
- getDeclaredMethods()
- getMethods()
- getDeclaredMethods()
Cat tom=new Cat(30,9);
Class c=tom.getClass();
Method m=c.getMethod("setLength", int.class);
m.invoke(tom, 31);
System.out.println(tom.toString());