package reflects; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import io.Person; //通过Relect反射方法创建对象,输出对象信息 public class ReflectDemo1 { public static void main(String[] args) { try { // 1、获得目标对象的类型 Class cl = Class.forName("io.Person"); // 2、获得对象的构造方法 Constructor ct = cl.getDeclaredConstructor(); // 3、创建对象 Person p = (Person) ct.newInstance(); // 4、获得对象的属性,赋值 Field name = cl.getDeclaredField("name"); Field age = cl.getDeclaredField("age"); Field gender = cl.getDeclaredField("gender"); // 5、设置属性访问权限,无论属性的访问修饰符是什么级别true表示可见 name.setAccessible(true); age.setAccessible(true); gender.setAccessible(true); // 6、设置属性的值 name.set(p, "Tom"); age.set(p, 20); gender.set(p, "男"); // 7、获得对象的方法 Method mt = cl.getDeclaredMethod("toShow", String.class); // 8、通过反射调用p对象的toshow方法 String st = (String) mt.invoke(p, "Refect反射"); System.out.println(st); } catch (Exception e) { e.printStackTrace(); } } } ********************************************************************************************** package io; import java.io.Serializable; //人类Person实现Serializable接口,实现序列化 public class Person implements Serializable { private String name;// 姓名 private Integer age;// 年龄 private String gender;// 性别 public Person() { } public Person(String name, Integer age, String gender) { this.name = name; this.age = age; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", gender=" + gender + "]"; } public String toShow(String st) { return "通过" + st + "方法调用输出:Person [name=" + name + ", age=" + age + ", gender=" + gender + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((gender == null) ? 0 : gender.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (gender == null) { if (other.gender != null) return false; } else if (!gender.equals(other.gender)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
时间: 2024-10-10 02:34:01