反射机制
2018-11-03 本文已影响0人
蓬莱辰
Java 反射机制是在运行状态中,对于任意一个类,都能够获得这个类的所有属性和方法,对于任意一个对象都能够调用它的任意一个属性和方法。这种在运行时动态的获取信息以及动态调用对象的方法的功能称为 Java 的反射机制。
1.获取class对象的三种方式:
类名.class;
对象.getClass();
Class.forName(类全名);ClassNotFoundException
2.获取构造函数对象
clazz.getConstructor();无参构造器
clazz.getConstructor(参数类型的class对象);带参构造,参数类型
Constructor constructor0 = clazz.getConstructor();// public class01.Person()
Constructor constructor1 = clazz.getConstructor(String.class);// public class01.Person(java.lang.String)
/**getConstructor(String.class,Integer.class)会抛出异常java.lang.NoSuchMethodException*/
Constructor<Person> constructor2 = clazz.getConstructor(String.class,int.class);//public class01.Person(java.lang.String,int)
System.out.println(constructor0);
System.out.println(constructor1);
System.out.println(constructor2);
Person person0 = (Person) constructor0.newInstance();
Person person1 = (Person) constructor1.newInstance("虚竹");
System.out.println(person1.getName());// 虚竹
3.获取属性
clazz.getField(属性名称);不能获取私有属性,否则会抛出异常NoSuchFieldException;
clazz.getDeclaredField()获取私有属性;
filed.setAccessible(true);设置私有属性可见
import java.lang.reflect.Field;
public class Reflect {
public static void main(String[] args) {
Class clazz = Person.class;
try {
Person person = (Person) clazz.newInstance();
System.out.println(clazz);// class class01.Person
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
System.out.println(field);// private java.lang.String class01.Person.name
field.set(person, "萧峰");
Object name = field.get(person);// 萧峰
System.out.println(name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.获取方法
异常:java.lang.NoSuchMethodException
getDeclaredMethod();获取私有方法
Method method0 = clazz.getMethod("fight", null);
Method method1 = clazz.getMethod("fight", String.class);
method0.invoke(person);// 左右勾拳
method1.invoke(person, "萧峰");//萧峰:降龙十八掌之亢龙有悔
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void fight() {
System.out.println("左右勾拳");
}
public void fight(String name) {
System.out.println(name+":降龙十八掌之亢龙有悔");
}
}