泛型方法+反射,解决重复代码问题
1.泛型方法声明
public <T> List<SigmaInstance> generateInstancesByDataInfoList(List<T> infoList,
Map<Long, GroupInfo> groupMap,
Map<String, AppInfo> appMap) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
}
2.使用范例
/**
* 基于传递过来的对象列表,不同对象获取不同的属性写到internalAddress属性中去
* @param infoList
* @param groupMap
* @param appMap
* @param <T>
* @return
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public <T> List<SigmaInstance> generateInstancesByDataInfoList(List<T> infoList,
Map<Long, GroupInfo> groupMap,
Map<String, AppInfo> appMap) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
List<SigmaInstance> sigmaInstances = Lists.newArrayList();
String getGroupIdMethodName = "getGroupId";
for (T devopsInstanceInfo:infoList) {
Method groupMethod = devopsInstanceInfo.getClass().getMethod(getGroupIdMethodName);
Long groupId = (Long) groupMethod.invoke(devopsInstanceInfo);
GroupInfo devopsGroupInfo = groupMap.get(groupId);
if (null == devopsGroupInfo){
LOG.warn("Get devopsGroupInfo error,devopsInstanceInfo: {}",JsonUtils.toJSONString(devopsInstanceInfo));
continue;
}
AppInfo devopsAppInfo = appMap.get(devopsGroupInfo.getAppEnName());
if (null == devopsAppInfo){
LOG.warn("Get devopsAppInfo error,devopsGroupInfo: {}",JsonUtils.toJSONString(devopsGroupInfo));
continue;
}
SigmaInstance sigmaInstance = new SigmaInstance();
sigmaInstance.setGroupEnName(devopsGroupInfo.getGroupName());
sigmaInstance.setAppEnName(devopsAppInfo.getAppEnName());
sigmaInstance.setPlatform(Platform.DEVOPS);
sigmaInstance.setEnv(generateEnvTypeByDevopsGroup(devopsGroupInfo));
Method getInternalAddressMethod = devopsInstanceInfo.getClass().getMethod(fieldMethodNameMap.get(devopsInstanceInfo.getClass()));
sigmaInstance.setInternalAddress((String) getInternalAddressMethod.invoke(devopsInstanceInfo));
sigmaInstance.setUseType(useTypeMap.get(devopsInstanceInfo.getClass()));
sigmaInstance.setCreateTime(new Date());
sigmaInstance.setCreateUser(DevopsProcessor.class.getSimpleName());
sigmaInstance.setUpdateTime(new Date());
sigmaInstance.setUpdateUser(DevopsProcessor.class.getSimpleName());
sigmaInstances.add(sigmaInstance);
}
return sigmaInstances;
}
原创:做时间的朋友