反射一共三种方法:
//假如有个类:Foo
三种方法如下:
Class cla = Foo.getClass();
Class cla = Foo.class ;
Class cla = Class.forName( "xx.xx.Foo" );
这几天温习aop的时候,发现要想掌握熟练还是需要深刻理解动态代理以及反射机制,所以就回头温习了下黑马的反射。
具体如下,其也是IOC核心思想的来源,在不主动创建类的时候,由反射机制给我们创建,我们只需要修改配置文件就可以决定创建哪个类,以及执行什么方法。
比如创建一个类Person
package domain;
@Data
public class Person {
private String name;
private int age;
public void eat() {
System.out.println("Person --- eating...");
}
public void eat(String food) {
System.out.println("you are eatting "+food);
}
}
然后以下就是反射的一些常用方法
package domain;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectDemo1 {
public static void main(String[] args) throws Exception{
Class personClass=Person.class;
Method eat = personClass.getMethod("eat");
Person p = new Person();
Object invoke = eat.invoke(p);
System.out.println(eat);
System.out.println("============================");
System.out.println(invoke);
System.out.println("============================");
Method eat1 = personClass.getMethod("eat", String.class);
Object invoke1 = eat1.invoke(p,"fan");
System.out.println(invoke1);
Method[] declaredMethods = personClass.getDeclaredMethods();
for (Method method :declaredMethods
) {
System.out.println(method);
}
Method[] methods = personClass.getMethods();
for (Method method:methods
) {
System.out.println(method);
}
Constructor constructor = personClass.getConstructor(String.class, int.class);
Object obj = constructor.newInstance("wangw", 5);
System.out.println(obj);
Constructor[] constructors = personClass.getConstructors();
for (Constructor c : constructors) {
System.out.println(c);
}
Field[] fields = personClass.getFields();//获取 public修饰的成员变量
for (Field field : fields
) {
System.out.println(field);
}
Field[] declaredFields = personClass.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field);
}
Class<?> cls1 = Class.forName("domain.Person");
//多用于配置文件
System.out.println(cls1);
System.out.println("====================");
Class cls2 = Person.class;
//多用于参数传递
System.out.println(cls2);
System.out.println("====================");
Person person = new Person();
//多用于对象获取字节码的方式
System.out.println(person.getClass());
}
}
最后以一个案例结尾