文章主旨,测试反射获取方法,属性
先写个测试的对象
package com.test; public class Stu{ private String name = "aabbcc"; private String address = "abcdefg"; public String ph = "black"; public String ps = "fff" ; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPh() { return ph; } public void setPh(String ph) { this.ph = ph; } public String getPs() { return ps; } public void setPs(String ps) { this.ps = ps; } public Stu(String name, String address, String ph, String ps) { super(); this.name = name; this.address = address; this.ph = ph; this.ps = ps; } public Stu() { super(); } public void m(){ } private void n(){ } }
package com.test; import java.lang.reflect.Field; public class TestClassMain { public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, ClassNotFoundException, IllegalAccessException { Stu st = new Stu(); Field fph = st.getClass().getField("ph"); //public java.lang.String com.test.Stu.ph //获取对象的公开属性 System.out.println(fph); // 获取对象的公开属性的值 System.out.println(fph.get(st)); //black // 有人说了,不知道人家的属性名字,看你怎么获取属性,和值,通过下面方法,就可以实现获取对象的属性和值 // 通过getFields() 可以获取所有的公开属性 Field[] fields = st.getClass().getFields(); for (Field field : fields) { System.out.println(field.get(st)); } // 通过getDeclaredFields() 获取所有的公开和私有的属性 Field[] fields2 = st.getClass().getDeclaredFields(); for (Field field : fields2) { field.setAccessible(true); System.out.println(field.get(st)); } // 获取对象的构造方法 , 只能获取公开的 Constructor<?>[] constructors = st.getClass().getConstructors(); for (Constructor<?> constructor : constructors) { System.out.println(constructor); } // 可以获取全部的构造方法 Constructor<?>[] dec = st.getClass().getDeclaredConstructors(); for (Constructor<?> d : dec) { d.setAccessible(true); System.out.println(d); } // 公共方法和私有方法 Method[] mes = st.getClass().getDeclaredMethods(); for (Method met : mes) { System.out.println(met); } //传对象 changeValue(st); }// 用来修改对象值 public static void changeValue(Object obj) throws IllegalArgumentException, IllegalAccessException{ Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { if(field.getType() == String.class){ field.setAccessible(true); String oldValue = (String)field.get(obj); String newVale = oldValue.replace('b','A'); field.set(obj, newVale); System.out.println(field.get(obj)); } } } }
剩下的自己测测,多练多测
不足之处,多多指导