标签:控制器 out getter hashmap 字段 public 实现 内省 static
package com; import java.io.Serializable; import java.util.Arrays; /** * 2017/11/2 * 说明: */ public class Student implements Serializable{ private String name ;//字段 private int age;//字段 private int[] aa; public int[] getAa() { return aa; } public void setAa(int[] aa) { this.aa = aa; } public String getName() {//读属性 return name; } public void setName(String name) {//写属性 this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ", aa=" + Arrays.toString(aa) + ‘}‘; } }
public void add(Student stu){}
public void add(String name,int age);
package com; import java.io.Serializable; import java.util.Arrays; /** * 2017/11/2 * 说明: */ public class Student implements Serializable{ private String name ;//字段 private int age;//字段 private int[] aa; public int[] getAa() { return aa; } public void setAa(int[] aa) { this.aa = aa; } public String getName() {//读属性 return name; } public void setName(String name) {//写属性 this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ", aa=" + Arrays.toString(aa) + ‘}‘; } }
package com; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * 2017/11/2 * 说明:内省技术来封装javaBean技术 */ public class StudentTest { public static void main(String[] args) throws Exception{ Student student = new Student(); Map<String,Object> properties = new HashMap<>(); properties.put("name","张三"); properties.put("age",20); properties.put("aa",new int[]{1,2}); populate(student,properties); System.out.println(student); } public static void populate(Object Obj,Map<String,Object> properties) throws Exception { BeanInfo beanInfo = Introspector.getBeanInfo(Obj.getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor pd : pds){ if(!pd.getName().equals("class")){ String property = pd.getName();//获取每一个属性值 Method method = pd.getWriteMethod(); //遍历properties 的Map集合 for(Iterator<Map.Entry<String,Object>> iterator = properties.entrySet().iterator();iterator.hasNext();){ Map.Entry<String,Object> entry = iterator.next(); String key = entry.getKey(); Object value = entry.getValue(); if(key.equals(property)){ method.invoke(Obj,value); } } } } } }
标签:控制器 out getter hashmap 字段 public 实现 内省 static
原文地址:http://www.cnblogs.com/xuweiweiwoaini/p/7777687.html