用泛型方法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__& ...
随机推荐
- 简单混合锁(HybridLock)
internal sealed class SimpleHybridLock : IDisposable { //基元用户模式构造使用 ; //基元内核模式构造 private AutoResetEv ...
- gulp connect.static is not a function
npm install --save serve-static var serveStatic = require('serve-static');
- Ubuntu 18.04 手动升级内核
一般情况下,系统正常更新,会自动升级内核到可用的最新版. 查看已安装的内核 $ sudo dpkg -l | grep linux-image 查看当前使用的内核 $ sudo uname -r 查看 ...
- Python的在线编辑环境
另外,再提供几个Python的在线编辑环境,可以直接写代码并且运行的环境. 在线Python实验室:http://www.pythoner.cn/labs/ 在线Python编辑器:http://ww ...
- C#学习之Timothy Liu
原文出自 本文摘录了一些值得学习的地方. 1.对一个程序来说,静态指编辑期.编译期,动态指运行期. 静态时装在硬盘里,动态时装在内存里. 2.反射示例 通过反射获得类的属性和方法. static vo ...
- Ion-select and ion-option list styling 自定义样式
https://forum.ionicframework.com/t/ion-select-and-ion-option-list-styling/117028
- [Python之路] 使用epoll实现高并发HTTP服务器
什么是epoll 我们在 Python多种方式实现并发的Web Server 的最后使用单进程+单线程+非阻塞+长连接实现了一个可并发处理客户端连接的服务器.他的原理可以用以下的图来描述: 解释: ...
- 【Python之路】特别篇--Python文件操作
文件操作 open函数,该函数用于文件处理 操作文件时,一般需要经历如下步骤: (1)打开文件 (2)操作文件 一.打开文件 文件句柄 = open('文件路径', '模式','编码') 打开文件时, ...
- java中子类继承父类时是否继承构造函数
来源:http://www.cnblogs.com/sunnychuh/archive/2011/09/09/2172131.html --------------------- java继承中对构造 ...
- 远程管理FTP
FTP默认路径 建立pub目录(注意不是文件) LeapFTP使用 注:上传到服务器的pub文件下,不要弄错目录. 在本地计算机利用LeapFTP与FTPServer进行数据的传输,但是FTPServ ...