1.先定义一个实体类
@Data
@Builder
public class CloudPrivateIndexVO {
@Schema(description = "丢包率")
private SortedMap<LocalDateTime, Double> lossMap;
@Schema(description = "平均时延")
private SortedMap<LocalDateTime, Double> avgDelay;
@Schema(description = "任务ID")
private Integer taskId;
@Schema(description = "资源池")
private String resourcePoolName;
@Schema(description = "可用区")
private String az;
}
2.get/set操作
(1)get的两种方式
public static <T> Object getValueMethod(T entity,String method) throws Exception {
// entity是实体,method是get方法,例如"getTaskId"
Class<?> tClass = entity.getClass();
Method method = tClass.getMethod(method);
Object value = method.invoke(entity);
return value;
}
public static <T> Object getValueField(T entity,String index) throws Exception {
// entity是实体, index是字段名称,例如"taskId"
Class<?> tClass = entity.getClass();
Field field = tClass.getDeclaredField(index);
field.setAccessible(true);
Object value = field.get(entity);
return value;
}
(2)反射获取实体的字段名称与对应的值
public void getNameAndValue(T entity) throws Exception{
Field[] fields = entity.getClass().getDeclaredFields();
for(Field field : fields){
field.setAccessible(true);
System.out.println("属性名: "+field.getName()+" 属性值: "+field.get(entity)); }
}
(3)实体中,lossMap已经存在/不存在,需要新加值的情况
public static <T> void setTaskIdField(T value) throws Exception {
Class<?> tClass = value.getClass();
Field field = tClass.getDeclaredField("lossMap");
field.setAccessible(true);
Object r = field.get(value);
if (r != null){
// 这里是为了判断Object是否是某个特定类型的实例,如果是就转为这个类型,这样写比直接强转符合规范
if (r instanceof SortedMap) {
SortedMap<?, ?> sortedMap = (SortedMap<?, ?>) r;
if (sortedMap.firstKey() instanceof LocalDateTime && sortedMap.get(sortedMap.firstKey()) instanceof String) {
SortedMap<LocalDateTime, String> result = (SortedMap<LocalDateTime, String>) sortedMap;
result.put(LocalDateTime.now(), "def");
}
}
}else{
SortedMap<LocalDateTime, Double> lossMap = Maps.newTreeMap(LocalDateTime::compareTo);
lossMap.put(LocalDateTime.now(),"def");
field.set(value,lossMap);
Map map = (Map) field.get(value);
System.out.println(map);
}
}