1、在JavaEE中,Java类的属性通过getter,setter来定义;
2、可使用BeanUtils工具包来操作Java类的属性:
--Beanutils是由Apache公司开发,能够方便对Bean类进行简便的操作
--涉及到的包:
(1) BeanUtils相关包
commons-beanutils-1.8.3.jar
commons-beanutils-1.8.3-javadoc.jar
commons-beanutils-1.8.3-javadoc.jar
commons-beanutils-bean-collections-1.8.3.jar
commons-beanutils-core-1.8.3.jar
(2) Logic4j相关包
commons-logging.jar
3、使用举例:
Bean类Customer:
public class Customer { private int id; private String name; private Date birth; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public Customer(int id, String name, Date birth) { super(); this.id = id; this.name = name; this.birth = birth; } public Customer() { } }
使用BeanUtils的setProperty()和getProperty()方法设置和获取属性:
public void testBeanUtils() throws Exception{ Customer customer = new Customer(); //设置customer的name属性 BeanUtils.setProperty(customer, "name", "Bob"); System.out.println(customer); //获取customer的属性值 String name = (String)BeanUtils.getProperty(customer, "name"); System.out.println(name); }
4、在JDBC中,当我们在编写DAO中的通用方法来进行查询时,可以使用BeanUtils类来为属性赋值(第32行):
1 public <T> T get(Class<T> clazz, String sql, Object ...args){ 2 T entity = null; 3 Connection conn = null; 4 PreparedStatement ps = null; 5 ResultSet rs = null; 6 try{ 7 conn = DAO.getConnection(); 8 ps = conn.prepareStatement(sql); 9 for(int i = 0; i < args.length; i++){ 10 ps.setObject(i + 1, args[i]); 11 } 12 13 rs = ps.executeQuery(); 14 Map<String, Object> map = new HashMap<String, Object>(); 15 ResultSetMetaData rsmd = rs.getMetaData(); 16 17 if(rs.next()){ 18 for(int i = 0; i < rsmd.getColumnCount(); i++){ 19 String columnLabel = rsmd.getColumnLabel(i + 1); 20 Object columnValue = rs.getObject(columnLabel); 21 22 map.put(columnLabel, columnValue); 23 } 24 } 25 26 if(map.size() > 0){ 27 entity = clazz.newInstance(); 28 for(Map.Entry<String, Object> entry : map.entrySet()){ 29 String fieldName = entry.getKey(); 30 Object value = entry.getValue(); 31 //使用BeanUtils工具类来为属性赋值 32 BeanUtils.setProperty(entity, fieldName, value); 33 /**使用反射的方式为属性赋值 34 Field field = clazz.getDeclaredField(key); 35 field.setAccessible(true); 36 field.set(entity, value);*/ 37 } 38 return entity; 39 } 40 41 }catch(Exception e){ 42 e.printStackTrace(); 43 }finally{ 44 if(rs != null){ 45 try { 46 rs.close(); 47 } catch (SQLException e) { 48 e.printStackTrace(); 49 } 50 } 51 if(ps != null){ 52 try { 53 ps.close(); 54 } catch (SQLException e) { 55 e.printStackTrace(); 56 } 57 } 58 if(conn != null){ 59 try { 60 conn.close(); 61 } catch (SQLException e) { 62 e.printStackTrace(); 63 } 64 } 65 } 66 return entity; 67 }