用泛型方法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__& ...
随机推荐
- [ZOJ 3610] Yet Another Story of Rock-paper-scissors
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4713 题目很水,但是注意,越是简单的题目越应该关注细节,比如说输出上 ...
- Excutor线程池
文章:Java并发(基础知识)—— Executor框架及线程池 待完善……
- less 分页显示文件内容
1.命令功能 less 是more的增强版,可以分页显示文件内容,而且less打开文件的速度要比vi,more更快.less支持搜索功能,显示行号. 2.语法格式 less option file ...
- java8 stream().map().collect()用法
有一个集合: List<User> users = getList(); //从数据库查询的用户集合 现在想获取User的身份证号码:在后续的逻辑处理中要用: 常用的方法我们大家都知道,用 ...
- Windows安装Redis并添加本地自启动服务
概况 在windows本地搭建redis缓存,添加到本地计算机的服务中,保证每次开机自动启动服务. 第一步:下载redis(我的是计算机win10,64位) https://github.com/Mi ...
- css 判断是iphone4s iphone5 加载不同样式
@media (device-height:480px) and (-webkit-min-device-pixel-ratio:2){/* 兼容iphone4/4s */ .class{}}@med ...
- Java之正则表达式来判断字符串中是否包含字母
/** * 使用正则表达式来判断字符串中是否包含字母 * @param str 待检验的字符串 * @return 返回是否包含 * true: 包含字母 ;false 不包含字母 */ public ...
- 四 java web考点
一.GET和POST区别(参考Servlet&JSP学习笔记) <form>中method属性默认为GET. 1.使用POST的情况 GET跟随URL之后,请求参数长度有限,过长的 ...
- EF 批量添加数据
原文:https://www.cnblogs.com/liuruitao/p/10049191.html 原文:https://www.cnblogs.com/yaopengfei/p/7751545 ...
- c++实例之通讯录管理系统之清空联系人功能(七)
#include<iostream> using namespace std; constexpr auto MAX = ; //联系人结构体 struct Person { string ...