Commons BeanUtil的介绍(抄录手册的说明):
The Bean Introspection Utilities component of the Apache Commons subproject offers low-level utility classes that assist in getting and setting property values on Java classes that follow the naming design patterns outlined in the JavaBeans Specification, as well as mechanisms for dynamically defining and accessing bean properties.
下面是我对Get 方法的一个简单实现:
1、属性工具类:
package test;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
public class MyPropUtil {
private static final char MAPPED_START = '(';
private static final char MAPPED_END = ')';
private static final char INDEXED_START = '[';
private static final char INDEXED_END = ']';
private static MyPropUtil instance;
private MyPropUtil() {
}
public static MyPropUtil getInstance() {
if (instance == null) {
instance = new MyPropUtil();
}
return instance;
}
/** *//** 获取简单属性 */
public Object getSimpleProperty(Object bean, String name) throws Exception {
String prop = this.getProperty(name);
PropertyDescriptor desc = this.getPropDesc(bean.getClass(), prop);
return desc.getReadMethod().invoke(bean, new Object[0]);
}
/** *//** 设置简单属性 */
public void setSimpleProperty(Object bean, String name, Object value) throws Exception {
String prop = this.getProperty(name);
PropertyDescriptor desc = this.getPropDesc(bean.getClass(), prop);
Object[] args = new Object[1];
args[0] = value;
desc.getWriteMethod().invoke(bean, args);
}
/** *//** 获取索引属性 */
public Object getIndexedProperty(Object bean, String name) throws Exception {
int index = this.getIndex(name);
String prop = this.getProperty(name);
PropertyDescriptor desc = this.getPropDesc(bean.getClass(), prop);
Object value = desc.getReadMethod().invoke(bean, new Object[0]);
if (value.getClass().isArray()) {
value = Array.get(value, index);
} else {
if (value instanceof List<?>) {
value = ((List<?>) value).get(index);
}
}
return value;
}
/** *//** 设置Map属性 */
public void setIndexedProperty(Object bean, String name, Object value) throws Exception {
int index = this.getIndex(name);
String prop = this.getProperty(name);
PropertyDescriptor desc = this.getPropDesc(bean.getClass(), prop);
Object array = desc.getReadMethod().invoke(bean, new Object[0]);
if (array.getClass().isArray()) {
Array.set(array, index, value);
} else {
if (array instanceof List) {
((List) array).set(index, value);
}
}
}
/** *//** 获取Map属性 */
public Object getMappedProperty(Object bean, String name) throws Exception {
String key = this.getKey(name);
String prop = this.getProperty(name);
PropertyDescriptor desc = this.getPropDesc(bean.getClass(), prop);
Object value = desc.getReadMethod().invoke(bean, new Object[0]);
if (value instanceof Map<?, ?>) {
value = ((Map<?, ?>) value).get(key);
}
return value;
}
public void setMappedProperty(Object bean, String name, Object value) throws Exception {
String key = this.getKey(name);
String prop = this.getProperty(name);
PropertyDescriptor desc = this.getPropDesc(bean.getClass(), prop);
Object map = desc.getReadMethod().invoke(bean, new Object[0]);
if (map instanceof Map) {
((Map) map).put(key, value);
}
}
private String getProperty(String s) {
for (int i = 0, size = s.length(); i < size; i++) {
char c = s.charAt(i);
if (c == MAPPED_START || c == INDEXED_START) {
return s.substring(0, i);
}
}
return s;
}
private PropertyDescriptor getPropDesc(Class<?> cls, String prop) throws IntrospectionException {
BeanInfo info = Introspector.getBeanInfo(cls);
PropertyDescriptor[] descs = info.getPropertyDescriptors();
PropertyDescriptor desc = null;
for (PropertyDescriptor pd : descs) {
if (prop.equals(pd.getName())) {
desc = pd;
break;
}
}
return desc;
}
private int getIndex(String s) {
for (int i = 0, size = s.length(); i < size; i++) {
char c = s.charAt(i);
if (c == INDEXED_START) {
int end = s.indexOf(INDEXED_END, i);
return Integer.parseInt(s.substring(i + 1, end));
}
}
return -1;
}
private String getKey(String s) {
for (int i = 0, size = s.length(); i < size; i++) {
char c = s.charAt(i);
if (c == MAPPED_START) {
int end = s.indexOf(MAPPED_END, i);
return s.substring(i + 1, end);
}
}
return null;
}
}
2、测试:
2-1、业务类:
package test;
import java.util.List;
import java.util.Map;
public class MyBean {
private String name;
private List<String> list;
private Map<String, String> map;
private int[] intArray;
public int[] getIntArray() {
return intArray;
}
public void setIntArray(int[] intArray) {
this.intArray = intArray;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public MyBean(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("name:").append(name);
sb.append(" list:[");
if (list != null && list.size() > 0) {
for (String temp : list) {
sb.append(temp).append(",");
}
}
sb.append("] map:(");
if (map != null && map.size() > 0) {
for (String temp : map.keySet()) {
sb.append(temp).append("-").append(map.get(temp)).append(",");
}
}
sb.append(") array:{");
if (intArray != null && intArray.length > 0) {
for (int i : intArray) {
sb.append(i).append(",");
}
}
sb.append("}");
return sb.toString();
}
}
2-2、测试类:
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BeanTest {
public static void main(String[] args) {
try {
testGet();
testSet();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testGet() throws Exception {
MyPropUtil util = MyPropUtil.getInstance();
MyBean bean = new MyBean("good");
System.out.println(util.getSimpleProperty(bean, "name"));
List<String> list = new ArrayList<String>();
list.add("list0");
bean.setList(list);
System.out.println(util.getIndexedProperty(bean, "list[0]"));
int[] intArray = { 1, 2, 3 };
bean.setIntArray(intArray);
System.out.println(util.getIndexedProperty(bean, "intArray[2]"));
Map<String, String> map = new HashMap<String, String>();
map.put("key", "value");
bean.setMap(map);
System.out.println(util.getMappedProperty(bean, "map(key)"));
}
public static void testSet() throws Exception {
MyPropUtil util = MyPropUtil.getInstance();
MyBean bean = new MyBean("good");
List<String> list = new ArrayList<String>();
list.add("list0");
bean.setList(list);
bean.setMap(new HashMap<String, String>());
bean.setIntArray(new int[3]);
util.setSimpleProperty(bean, "name", "namegood");
util.setIndexedProperty(bean, "list[0]", "listgoodvalue");
util.setIndexedProperty(bean, "intArray[0]", 3);
util.setMappedProperty(bean, "map(key)", "value");
System.out.println(bean);
}
}
输出如下:
good
list0
3
value
name:namegood list:[listgoodvalue,] map:(key-value,) array:{3,0,0,}