01: /*
02: * @(#)BeanUtil.java 1.2 04/12/06
03: *
04: * Copyright (c) 2003, 2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package pnuts.beans;
10:
11: import java.util.*;
12: import java.beans.*;
13: import java.lang.reflect.*;
14: import pnuts.compiler.DynamicRuntime;
15:
16: /**
17: * This class provides utility methods to access Bean properties.
18: */
19: public class BeanUtil {
20:
21: private final static DynamicRuntime rt = new DynamicRuntime();
22:
23: protected BeanUtil() {
24: }
25:
26: /**
27: * Gets a bean property
28: *
29: * @param bean the Bean
30: * @param property the bean property
31: * @return the bean property
32: */
33: public static Object getProperty(Object bean, String property)
34: throws IllegalAccessException {
35: return rt.getBeanProperty(bean, property);
36: }
37:
38: /**
39: * Sets a bean property
40: *
41: * @param bean the Bean
42: * @param property the bean property
43: * @param value the value of the bean property
44: */
45: public static void setProperty(Object bean, String property,
46: Object value) throws IllegalAccessException,
47: InvocationTargetException {
48: rt.setBeanProperty(bean, property, value);
49: }
50:
51: /**
52: * Gets a bean property type
53: *
54: * @param cls the class
55: * @param property the property name
56: * @return the type of the bean property
57: */
58: public static Class getPropertyType(Class cls, String property) {
59: return rt.getBeanPropertyType(cls, property);
60: }
61:
62: public static void setProperties(Object bean, Map map)
63: throws IntrospectionException, IllegalAccessException,
64: InvocationTargetException {
65: BeanInfo info = Introspector.getBeanInfo(bean.getClass());
66: PropertyDescriptor[] props = info.getPropertyDescriptors();
67: Set keySet = map.keySet();
68:
69: for (int j = 0; j < props.length; j++) {
70: PropertyDescriptor p = props[j];
71: String name = p.getName();
72: if (keySet.contains(name)) {
73: Object value = map.get(name);
74: Method m = p.getWriteMethod();
75: if (m != null) {
76: rt.setBeanProperty(bean, name, value);
77: }
78: }
79: }
80: }
81: }
|