我们新建一个类Person:
package person; import sex.Sex; public class Person{ private String name = null; private int age = 0; private Sex sex = null; private String birthday = null; public Person(){}; public Person(String name, int age, Sex sex, String birthday){ String birMatch = "\\d{4}-\\d{2}-\\d{2}"; this.name = name; this.age = age; this.sex = sex; if(birthday.matches(birMatch)){ this.birthday = birthday; } } public void setInfo(String name, int age, Sex sex, String birthday){ String birMatch = "\\d{4}-\\d{2}-\\d{2}"; this.name = name; this.age = age; this.sex = sex; if(birthday.matches(birMatch)){ this.birthday = birthday; } } public void setName(String name){ this.name = name; } public void setAge(int age){ this.age = age; } public void setSex(Sex sex){ this.sex = sex; } public void setBirthday(String birthday){ this.birthday = birthday; } public String getName(){ return this.name; } public int getAge(){ return this.age; } public Sex getSex(){ return this.sex; } public String getBirthday(){ return this.birthday; } public String toString(){ return this.name + ", " + this.age + " years old, " + this.sex + ", " + this.birthday; } }
新建一个枚举Sex:
package sex; public enum Sex{ MALE, FEMALE; }
在Main.java主方法中获取Person类的属性:
package main; import java.lang.reflect.Field; import java.lang.reflect.Method; import person.Person; import sex.Sex; public class Main { public static void main(String[] args){ Class<?> cls = null; Object obj = null; try { cls = Class.forName("person.Person"); obj = cls.newInstance(); Field var1 = cls.getDeclaredField("name"); var1.setAccessible(true); //设置该属性能被外部访问 var1.set(obj, "XiaoBiqiang"); System.out.println(var1.get(obj)); var1.setAccessible(false); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行结果:
XiaoBiqiang
注意:使用反射操作属性时最好通过setter和getter方法,因为扩大了属性的访问权限可能造成不安全