/**
* 根據swagger ApiModelProperty 註解類的 example 實例化 實體
* @param clazz 實體類
* @param <T> 返回實例化的數據
* @return 返回實例化的數據
*/
public static <T> T mockExampleModel(Class<T> clazz){
try {
T resultT = clazz.newInstance();
Map<String,Object> exampleFieldMap = new HashMap<>();
Field[] fields = clazz.getDeclaredFields();//獲取所有的屬性 包括公有和私有
for (Field field : fields){
//獲取 ApiModelProperty 註解
ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
if(apiModelProperty != null){
//獲取 ApiModelProperty 註解下的 example值
String example = apiModelProperty.example();
if( !example.equals("")){
exampleFieldMap.put(field.getName(),example);
}
}
}
return map2Bean(clazz,exampleFieldMap);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
/**
* 根據 傳入的map與類名,通過反射實例化對象
* @param clazz 需要實例化的類
* @param map 包含屬性的鍵值對 (String,Object)
* @return 實例化成功的對象
*/
public static <T> T map2Bean(Class<T> clazz, Map<String,Object> map){
T obj=null;
try {
//根據類名實例化對象
obj=clazz.newInstance();
for(String key :map.keySet()){
if(key!=null&&!"".equals(key)){
//將屬性首字符大寫
Character c=key.charAt(0);
c=Character.toUpperCase(c);
String temp=String.valueOf(c);
if(key.length()>1)
temp+=key.substring(1);
Method methods[]=obj.getClass().getMethods();
for(int i=0;i<methods.length;++i){
//判斷方法名是否匹配
if(methods[i].getName().equal("set"+temp))
{
//執行方法,傳入值
methods[i].invoke(obj, map.get(key));
break;
}
}
}
}
// Method method=obj.getClass().getMethod("toString");
// method.invoke(obj, null);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return obj;
}