①加载类[3个方式]
Person有2个属性,name和age,最后会给出Person类的信息
Class clazz1 = Class.forName("Person");
Class clazz2 = Person.class;
Person p = new Person();
Class clazz3 = p.getClass();
②构造器Constructor
<span style="white-space:pre"> </span>Constructor c = clazz.getConstructor(null);//获取的是无参构造
Person person1 = (Person) c.newInstance(null);
System.out.println(person1.name);
<span style="white-space:pre"> </span>Constructor c1 = clazz.getConstructor(String.class);//获取String参数的构造
Person p2 = (Person) c1.newInstance("a"); //给参数,实例化
System.out.println(p2.name);
Constructor c1 = clazz.getDeclaredConstructor(String.class,int.class);
c1.setAccessible(true); //暴力反射,因为这里的构造是私有的,不设置会报错
Person p2 = (Person) c1.newInstance("a",12);
System.out.println(p2.name);
<span style="white-space:pre"> </span>//Person中的私有构造函数
<span style="white-space:pre"> </span>private Person(String name,int age){
<span style="white-space:pre"> </span>System.out.println("name & age 构造函数");
<span style="white-space:pre"> </span>}
③方法Method
<span style="white-space:pre"> </span>Person person = new Person(); //这里给出接下来要执行方法的对象
Method m = clazz.getMethod("get", String.class);//get是Person类中已经定义的方法名,后面是参数类型
m.invoke(person, "coci");//执行方法
<span style="white-space:pre"> </span>Method method = clazz.getMethod("set", String.class,int.class);
Object object = method.invoke(person, "csq",21); //后面2个是给出方法执行的参数
System.out.println("返回值 = "+object);
④域Field
<span style="white-space:pre"> </span>Field field = clazz.getField("name");//<span style="font-family: Arial, Helvetica, sans-serif;">getField,只能得到公有的域</span>
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>System.out.println(field.getType()); //得到域的类型
<span style="white-space:pre"> </span>if(field.getType().equals(String.class)){
<span style="white-space:pre"> </span>field.set(person, "value");
<span style="white-space:pre"> </span>System.out.println(field.get(person));
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>Field field2 = clazz.getDeclaredField("age");//<span style="font-family: Arial, Helvetica, sans-serif;">getDeclaredField,这个方法可以得到私有的域&公有的域</span>
<span style="white-space:pre"> </span>field2.setAccessible(true);
<span style="white-space:pre"> </span>System.out.println(field.get(person)+"=="+field2.get(person));
Person
class Person{
public String name = "coci";
private int age = 18;
public Person(){
System.out.println("无参构造");
}
public Person(String name){
System.out.println("name 构造函数");
}
private Person(String name,int age){
System.out.println("name & age 构造函数");
}
public void get(String name){
System.out.println("get方法==name="+name);
}
public static void get(){
System.out.println("static get方法==name=");
}
public int set(String name,int age){
System.out.println("set方法,有返回值"+name+"=="+age);
return 1;
}
}