package com.a;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Person{
private String name;
private int age;
public Person(){};
public Person(String name){
this.setName(name);
}
public Person(String name,int age){
this(name);
this.setAge(age);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void show(){
System.out.println(this.name+" "+this.age);
}
}
public class Test1 {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, InstantiationException, NoSuchFieldException{
Class ps=Person.class;
System.out.println(ps.getName());
/*
* 使用反射调用构造函数建立对象
*/
Constructor mt1=ps.getConstructor(String.class,int.class);//获取构造函数的方法,参数:空不填,其他为类型.class
System.out.println(mt1);//打印得到的构造函数的方法名
Person per=(Person) mt1.newInstance("jiengyh",20);//通过得到的构造器的newInstance方法来建立对象,括号中的参数为构造函数的参数。
per.show();
//通过反射获取并操作方法
Method mt=ps.getMethod("setName",String.class); //获取指定的公有方法,括号内的参数为,第一个是方法名称,以后为传入参数的数据类型加.class
mt.invoke(per, "huazehui");
per.show();
//通过反射,修改属性值
Field f=ps.getDeclaredField("name");
f.setAccessible(true);
f.set(per, "jiengyh520");
Field f1=ps.getDeclaredField("age");
f1.setAccessible(true);
f1.set(per, 25);
per.show();
/*
* 把所有的构造函数放在一个Constructor[]数组中并遍历打印
Constructor[] mt=ps.getConstructors();
for(Constructor c:mt){
System.out.println(c);
}
*/
}
}
反射基础
最新推荐文章于 2021-06-15 20:41:07 发布