根據物件中欄位屬性值,動態java反射呼叫相應的get方法
阿新 • • 發佈:2019-01-09
根據物件中欄位屬性值,動態呼叫相應的get方法
#### 舉個例子,把物件GoodsVO中的欄位作為key, get方法作為value,全部存放在Map中.
//商品物件
public class GoodsVO {
/**
* 品牌ID
*/
private Long brandId;
/**
* 品牌名稱
*/
private String brandName;
/**
* 商品ID
*/
private Long goodsId;
/**
* 商品標籤
*/
private List<String> goodsTagList;
/**
* 庫存
*/
private Integer actualStore;
/**
* 狀態 0 下架 1 上架
*/
private Integer status;
public GoodsVO() {
}
public GoodsVO(String brandName, Long brandId,Long goodsId, Integer actualStore, Integer status, List<String> goodsTagList) {
this .brandName = brandName;
this.goodsId = goodsId;
this.brandId = brandId;
this.actualStore = actualStore;
this.status = status;
this.goodsTagList = goodsTagList;
}
set/get。。。。
}
實際情況我們可以採用笨方法,一個一個的put到map中,但是這不是我們今天想要學習的。
採用java反射實現
/**
* @author zhanghuilong
* @desc
* @since 2018/06/12
*/
public class Test {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
GoodsVO goodsVO = new GoodsVO("蘋果",1L,100L,101, 1,asList("����-Apple","果粉","Mac系列\n"));
Class<?> aClass = GoodsVO.class;
Field[] fields = aClass.getDeclaredFields();
Map<Object, Object> map = new HashMap<>();
for (Field field : fields){
map.put(field.getName() , getResult(field.getName() , goodsVO));
}
System.out.println(JSON.toJSONString(map));
}
private static Object getResult(Object fieldName, GoodsVO goodsVO) {
try {
Class<?> aClass = goodsVO.getClass();
Field declaredField = aClass.getDeclaredField(fieldName.toString());
declaredField.setAccessible(true);
PropertyDescriptor pd = new PropertyDescriptor(declaredField.getName(), aClass);
Method readMethod = pd.getReadMethod();
return readMethod.invoke(goodsVO);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
輸出結果: