Java中反射和内省代码实例
反射
我们建立一个Person类,对此进行反射操作。
package myReflection; public class Person { private String name; private String id; Person(){} /** * @param name * @param id */ public Person(String name, String id) { super(); this.name = name; this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } }
分别对constructor‘、属性和方法反射
test1====无参数构造函数
test2 ====有参数构造函数
test3=====属性
test4=====方法
package myReflection; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.junit.Test; public class useReflection { public static void main(String[] args) throws ClassNotFoundException { // TODO Auto-generated method stub Class c1=Person.class; Class c2=new Person().getClass(); Class c3=Class.forName("myReflection.Person"); } @Test public void test4() throws Exception{ Class c=Class.forName("myReflection.Person"); Person p=(Person) c.newInstance(); Method m=c.getDeclaredMethod("setName", String.class); m.invoke(p, "Lannister"); System.out.println(p.getName()); } @Test public void test3() throws Exception{ try { Class c=Class.forName("myReflection.Person"); Person p=(Person) c.newInstance(); Field f1=c.getDeclaredField("name"); f1.setAccessible(true); f1.set(p, "Stark"); System.out.println(f1.get(p)); } catch (Exception e) { // TODO: handle exception } } @Test public void test2() throws Exception { Class c=Class.forName("myReflection.Person"); Constructor cs=c.getConstructor(String.class,String.class); Person p1=(Person)cs.newInstance("Jon","Snow"); System.out.println(p1.getId()+" "+p1.getName()); } @Test public void test1() throws Exception{ Class cl3=Class.forName("myReflection.Person"); Person p =(Person)cl3.newInstance(); p.setName("Tully"); System.out.println(p.getName()); } }
内省
目的:将Map中的数据封装到一个JavaBean对象中去。
class User { private String username; private String password; public User(String username, String password) { this.username = username; this.password = password; } public User() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String toString() { return "User [username=" + username + ", password=" + password + "]"; } } Map<String,String> map=new HashMap<String,String>(); map.put("username", "admin"); map.put("password", "admin123"); BeanInfo bi=Introspector.getBeanInfo(User.class); PropertyDescriptor[] pds=bi.getPropertyDescriptors(); User user=new User(); for(PropertyDescriptor pd:pds) { String name=pd.getName(); String value=map.get(name); System.out.println("name value pair "+name +": "+value); if(value!=null) { //wm write method Method wm=pd.getWriteMethod(); wm.invoke(user, value); } } System.out.println(user.toString());
输出
name value pair class: null name value pair password: admin123 name value pair username: admin User [username=admin, password=admin123]
每个PropertyDescriptor对象对应一个JavaBean属性:
l String getName():获取JavaBean属性名称;
l Method getReadMethod:获取属性的读方法;
l Method getWriteMethod:获取属性的写方法。
使用commons-beanutils可以简化内省的操作
例子
设置属性
User user=new User();
BeanUtils.setProperty(user,"username","admin");
获取JavaBean属性
User user=new User("admin","12334");
String username=BeanUtils.getProperty(user,"username");
把Map数据封装到JavaBean对象中
Map<String,String> map=new HashMap<String,String>();
map.put("username", "admin");
map.put("password", "admin123");
User user=new User();
BeanUtils.populate(user,map);
等等