用泛型方法Java从实体中提取属性值,以及在泛型方法中的使用
public <T> T getFieldValue(Object target, String fieldName, Class<T> typeName)
{
try {
Object fieldValue = FieldUtils.readField(target, fieldName, true);
return (T)fieldValue;
} catch (IllegalAccessException e) {
log.error("出错:实体类{}没有{}类型的{}属性字段!",target.getClass(),typeName.getSimpleName(),fieldName);
throw new RuntimeException(e);
}
}
用法1:
public Long getLongValue(Object target, String fieldName)
{
return getFieldValue(target,fieldName,Long.class);
}
以此类推,你也可以写出
public LocalDateTime getLocalDateTimeValue(Object target, String fieldName)
{
return getFieldValue(target,fieldName,LocalDateTime.class);
} public String getStringValue(Object target, String fieldName)
{
return getFieldValue(target,fieldName,String.class);
}
笔者的一个用法是在泛型方法中提取实体的属性值,做进一步计算
<R,T> 你的返回类型 processData(String label, String snapshotKey, Class<T> targetClass,
Predicate<? super T> filter, final Function<? super T, ? extends R> mapper)
{
if(filter == null)
{
//如果没有指定过滤表达式,给一个默认值
filter = (T entity)->{
LocalDateTime createTime = cacheService.getFieldValue(entity, "createTime", LocalDateTime.class);
return createTime.getMinute() % 10 == 0
&&createTime.getSecond() ==0;
};
}
Map<String,Object> resultMap = new HashMap<>();
Optional<SnmpNode> node1 = nodeMapping.values().stream().findFirst();
List<T> list = null;
if(node1.isPresent())
{
String ipAddr1 = node1.get().getAddress();
list = cacheService.getCachedList(snapshotKey, ipAddr1, targetClass);
//服务器ip
resultMap.put("legend", nodeMapping.values().stream().map(SnmpNode::getAddress).collect(Collectors.toList())); //批量格式时间MM-dd HH:mm:ss并封送到List
List<String> xAxis = list.stream()
.map(entity->cacheService.getFieldValue(entity,"createTime", LocalDateTime.class))
.filter(
localDateTime -> localDateTime.getMinute()%10==0 && localDateTime.getSecond() == 0
).map(createTime -> createTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm"))).collect(Collectors.toList()); //筛选后的样本大小
int filteredSize = xAxis.size(); //由于图表不能显示太多的数据,太多的就会被隐藏,因此只显示最近的20条数据
xAxis = xAxis.stream().skip(filteredSize>=0?filteredSize-20:filteredSize).collect(Collectors.toList());
resultMap.put("xAxis",xAxis); List<EChartSeries> series = new LinkedList<>();
for(Map.Entry<Long,SnmpNode> entry: nodeMapping.entrySet())
{
SnmpNode node = entry.getValue(); String ipAddr = node.getAddress(); List<T> traffics = cacheService.getCachedList(snapshotKey, ipAddr, targetClass); List<R> data = traffics.stream()
.filter(filter)
.skip(filteredSize>=0?filteredSize-20:filteredSize)
.map(mapper).collect(Collectors.toList()); EChartSeries chartSeries = new EChartSeries.Builder()
.withName(ipAddr)
.withStack(label)
.withType("line")
.withData((LinkedList<String>) new LinkedList<R>(data))
.build(); if(!CollectionUtils.isEmpty(data)) {
series.add(chartSeries);
}
}
resultMap.put("series",series);
}
return 你的返回类型;
}
import lombok.Data;
import lombok.NoArgsConstructor; import java.util.LinkedList; /***
* // name:'邮件营销',
* // type:'line',
* // stack: '内存使用率',
* // data:[120, 132, 101, 134, 90, 230, 210]
*/
@Data
@NoArgsConstructor
public class EChartSeries {
private String name;
private String type;
private String stack;
private LinkedList<String> data; private EChartSeries(Builder builder) {
setName(builder.name);
setType(builder.type);
setStack(builder.stack);
setData(builder.data);
} public static final class Builder {
private String name;
private String type;
private String stack;
private LinkedList<String> data; public Builder() {
} public Builder(EChartSeries copy) {
this.name = copy.getName();
this.type = copy.getType();
this.stack = copy.getStack();
this.data = copy.getData();
} public Builder withName(String name) {
this.name = name;
return this;
} public Builder withType(String type) {
this.type = type;
return this;
} public Builder withStack(String stack) {
this.stack = stack;
return this;
} public Builder withData(LinkedList<String> data) {
this.data = data;
return this;
} public EChartSeries build() {
return new EChartSeries(this);
}
}
}
用泛型方法Java从实体中提取属性值,以及在泛型方法中的使用的更多相关文章
- java 获取实体类对象属性值的方法
在java中我们要获得实体类对象的属性,一般情况是将实体类中的属性私有化,然后再对外提供get()与set()方法,然后再获取实体类对象的属性的时候先把对象new出来,再用变量名.get()的方法得到 ...
- java 中利用反射机制获取和设置实体类的属性值
摘要: 在java编程中,我们经常不知道传入自己方法中的实体类中到底有哪些方法,或者,我们需要根据用户传入的不同的属性来给对象设置不同的属性值,那么,java自带的反射机制可以很方便的达到这种目的,同 ...
- 【转】java遍历实体类的属性和数据类型以及属性值
和同学接了个外包的活,由于项目中很多地方要用到poi导出excel,而每次导出都要写很多相同的代码,因为poi的cell.setCellValue();每次设置的都是不同实体bean的属性值,导致代码 ...
- java怎么比较两个实体类的属性值
分享一下比较两个实体类的工具包 package cn.mollie.utils; import java.beans.Introspector; import java.beans.PropertyD ...
- java反射获取和设置实体类的属性值 递归所有父类
最近做一个通用数据操作接口,需要动态获取和设置实体类的属性值,为了通用实体做了多重继承,开始网上找到代码都不支持父类操作,只能自己搞一个工具类了,此工具类可以设置和获取所有父类属性,代码贴下面拿走不谢 ...
- Spring中使用@Value读取porperties文件中的属性值方法总结及注意事项
本文为博主原创,转载请注明出处. 此前曾总结过使用工具类读取properties文件中的属性值,有兴趣的可以看一下. 如何快速获取properties中的配置属性值:https://www.cnblo ...
- <s:property="a" value=""/>取的<s:debug></s:debug>中的value stack中的属性值
<s:property="a" value=""/>取的<s:debug></s:debug>中的value stack中 ...
- 将source类中的属性值赋给target类中对应的属性
/** * 对象的属性值拷贝 * <p> * 将source对象中的属性值赋值到target对象中的属性,属性名一样,类型一样 * <p> * example: * <p ...
- 【Python】获取翻页之后的各页面中的属性值。
如何获取翻页之后的页面中的html标签中的属性值? # coding=utf-8 from selenium import webdriver if __name__=="__main__& ...
随机推荐
- 内核模式构造-Event构造(WaitLock)
internal sealed class SimpleWaitLock:IDisposable { //Enter()和Leave()中使用m_AutoResetEvent都将迫使调用线程做用户模式 ...
- Python:面向对象编程2
types.MethodType __slot__ @property, @xxx.setter Python的多重继承和MinIn 如何在class创建后,给实例绑定属性和方法? (动态绑定/定义 ...
- 平衡搜索树-B树。
B Tree 系列 摘录: https://blog.csdn.net/v_JULY_v/article/details/6530142 B+树介绍 B+树的几点介绍 动态查找树有: 二叉查找树,自平 ...
- mybatic进阶遗留
参考文章: MyBatis的架构设计以及实例分析 MyBatis缓存机制的设计与实现 MyBatis的一级缓存实现详解 及使用注意事项 MyBatis的二级缓存的设计原理
- (六)监控磁盘IO
(1)被监控端配置 #vi /etc/zabbix/zabbix_agentd.conf UnsafeUserParameters= UserParameter=custom.vfs.dev.read ...
- js实现网页上图片循环播放
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/T ...
- B/S文件夹上传下载组件
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 先说下要求: PC端全平台支持,要求支持Windows,Mac,Linux 支持所 ...
- 顺序表应用4-2:元素位置互换之逆置算法(数据改进)(SDUT 3663)
Problem Description 一个长度为len(1<=len<=1000000)的顺序表,数据元素的类型为整型,将该表分成两半,前一半有m个元素,后一半有len-m个元素(1&l ...
- DOM对象属性
事件 onmouseover 鼠标以上事件 onmouseout 鼠标离开事件 onclock 鼠标点击事件 onfocus 获取焦点 onblur 失去焦点 oninput 输入事件 ...
- 谷歌protocolbuff使用说明步骤
Protocolbuff 目录 1 Protocolbuff定义和作用... 1 2 Protocolbuff的使用步骤... 1 3 .proto编写格式... ...