反射demo

来源:互联网 发布:泰达网络wifi 编辑:程序博客网 时间:2024/05/22 00:40
import java.lang.reflect.Method;


public class Demo1 {

public static void main(String[] args) throws Exception {

//将Student 类里的对象复制到一个新的Student对象里(两种方法,1 通过压制权限 修改。2 通过拿到set方法 改)

//第一步 创建一个Student类型的对象
Student s1 = new Student("Tom",1,18);
System.out.println(s1);
//第二步  取到s1中的每个属性的值
//1.拿到Student的字节码文件
Class<?> class1 = Student.class;//s1.getClass()
//2.Field
/*Field field1 = class1.getDeclaredField("name");
field1.setAccessible(true);
String name = (String) field1.get(s1);
Field field2 = class1.getDeclaredField("id");
field2.setAccessible(true);
int id = (Integer) field2.get(s1);
Field field3 = class1.getDeclaredField("age");
field3.setAccessible(true);
int age = (Integer) field3.get(s1);*/
//3.Method
Method method = class1.getDeclaredMethod("getName");
String name = (String) method.invoke(s1);
Method method2 = class1.getDeclaredMethod("getId");
int id = (Integer) method2.invoke(s1);
Method method3 = class1.getDeclaredMethod("getAge");
int age = (Integer) method3.invoke(s1);
//第三步  创建新的对象,把值赋值给新的对象
Student s2 = (Student) class1.getConstructor(new Class[]{String.class,int.class,int.class}).newInstance(new Object[]{name,id,age});
System.out.println("复制成功");
System.out.println(s2.toString());
}
}
class Student{
private String name;
private int id;
private int age;
public Student(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
0 0
原创粉丝点击