Person类
package day1;
public class Person {
private String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
private Person(String name) {
this.name = name;
}
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;
}
@Override
public String toString() {
return "姓名:"+ name + ",年龄:" + age;
}
public String show(){
return this.name+" , "+this.age;
}
private String showNation(String nation){
return "我来自"+nation;
}
}
利用反射机制操作Person对象
package day1;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionDemo1 {
//反射机制,允许程序在运行期间获取类的内部信息,操作对象的内部属性和方法
//加载类后,产生Class类对象,含有类的完整信息
public static void main(String[] args) throws Exception {
Person p1=new Person("张三",20);
p1.age=30;
System.out.println(p1.show());
//通过反射,创建对象
Class c1=Person.class;
Constructor cons=c1.getConstructor(String.class,int.class);
Person p2=(Person) cons.newInstance("李四",40);
System.out.println(p2);
//调用对象的指定属性
Field age=c1.getDeclaredField("age");
age.set(p2,50);
System.out.println(p2);
//调用指定方法
Method show=c1.getDeclaredMethod("show");
System.out.println(show.invoke(p1));
//通过反射,可以调用Person类的私有结构,如私有构造器、属性、方法
System.out.println("******************************");
Constructor cons1=c1.getDeclaredConstructor(String.class);
cons1.setAccessible(true);
Person p3=(Person) cons1.newInstance("WangWu");
System.out.println(p3);
Field name=c1.getDeclaredField("name");
name.setAccessible(true);
name.set(p3,"ZhaoLiu");
System.out.println(p3);
Method showNation=c1.getDeclaredMethod("showNation", String.class);
showNation.setAccessible(true);
System.out.println(showNation.invoke(p3,"中国"));
}
}
标签:反射,name,age,Person,println,机制,public,String
From: https://www.cnblogs.com/fighterk/p/16934779.html