日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

反射调用 java bean的set和get方法

發布時間:2023/12/6 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 反射调用 java bean的set和get方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

v一、使用java.beans.PropertyDescriptor

import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method;public class PropertyUtil {private static final String SET_PREFIX = "set";private static final String IS_PREFIX = "is";private static final String GET_PREFIX = "get";public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName) {//根據需求,定制 自己的get和set方法Method setMethod = null;Method getMethod = null;PropertyDescriptor pd = null;try {Field field = clazz.getDeclaredField(propertyName);// 根據字段名來獲取字段if (field != null) {// 構建方法的后綴String methodEnd = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);setMethod = clazz.getDeclaredMethod(SET_PREFIX + methodEnd, new Class[] { field.getType() });// 構建get 方法getMethod = clazz.getDeclaredMethod(GET_PREFIX + methodEnd, new Class[] {});// 構建一個屬性描述器 把對應屬性 propertyName 的 get 和 set 方法保存到屬性描述器中pd = new PropertyDescriptor(propertyName, getMethod, setMethod);}} catch (Exception ex) {ex.printStackTrace();}return pd;}public static PropertyDescriptor getPropertyDescriptor2(Class<?> clazz, String propertyName) {//使用 PropertyDescriptor 提供的 get和set方法try {return new PropertyDescriptor(propertyName, clazz);} catch (IntrospectionException e) {e.printStackTrace();}return null;}public static void setProperty(Object obj, String propertyName, Object value) {Class<?> clazz = obj.getClass();// 獲取對象的類型PropertyDescriptor pd = getPropertyDescriptor(clazz, propertyName);// 獲取// clazz// 類型中的// propertyName// 的屬性描述器Method setMethod = pd.getWriteMethod();// 從屬性描述器中獲取 set 方法try {setMethod.invoke(obj, new Object[] { value });// 調用 set// 方法將傳入的value值保存屬性中去} catch (Exception e) {e.printStackTrace();}}public static Object getProperty(Object obj, String propertyName) {Class<?> clazz = obj.getClass();// 獲取對象的類型PropertyDescriptor pd = getPropertyDescriptor(clazz, propertyName);// 獲取// clazz// 類型中的// propertyName// 的屬性描述器Method getMethod = pd.getReadMethod();// 從屬性描述器中獲取 get 方法Object value = null;try {value = getMethod.invoke(clazz, new Object[] {});// 調用方法獲取方法的返回值} catch (Exception e) {e.printStackTrace();}return value;// 返回值 }}

v二、使用收藏的一個工具類 BeanHelper

  查看代碼

v三、獲取一個類每個屬性的?PropertyDescriptor

 org.springframework.beans.BeanUtils

  PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);

  使用請參考?這里










本文轉自 小眼兒 博客園博客,原文鏈接:http://www.cnblogs.com/hujunzheng/p/6778223.html,如需轉載請自行聯系原作者

總結

以上是生活随笔為你收集整理的反射调用 java bean的set和get方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。