根据泛型实体类和参数名获取参数值
接口类BaseB
/**
* @Description: 获取泛型类变量
* @author: jiahao
* @Date: 2019/8/6 17:25
*/
public interface Base<T> {
/**
* @param variable : 变量名称
* @description 根据泛型类和变量名称获取变量值
* @author jia hao
* @Date 2019/8/6 16:51
*/
String getVariable(T t, String variable);
}
实现类GenericsUtils
/**
* @Description: 泛型工具类
* @author: jiahao
* @Date: 2019/8/6 16:19
*/
public class GenericsUtils<T> implements Base<T> {
/**
* @param t : 泛型类
* @param variable : 变量名称
* @description 根据泛型类和变量名称获取变量值
* @author jia hao
* @Date 2019/8/6 16:51
*/
@Override
public String getVariable(T t, String variable) {
Class<?> beanClass = t.getClass();
try {
// 获取属性值(方法一)
PropertyDescriptor pd = new PropertyDescriptor(variable, beanClass);
Method rm = pd.getReadMethod();
return rm.invoke(t).toString();
// // 获取属性值(方法二)
// Field filed = t.getClass().getDeclaredField(variable);
// filed.setAccessible(true);
// return filed.get(t).toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
测试
public static void main (String[] args){
ExcelTraceVO vo = new ExcelTraceVO();
vo.setLon(11.11);
GenericsUtils tool = new GenericsUtils();
final String lon = tool.getVariable(vo, "lon");
System.out.println(lon);
}
结果为
11.11
实体类ExcelTraceVO
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class ExcelTraceVO {
/**
* 经度
*/
private Double lon;
/**
* 纬度
*/
private Double lat;
/**
* 排序
*/
private Integer sort;
}
参考: https://blog.csdn.net/Mr_yangzc/article/details/84643676