用泛型方法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);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM