關于java 泛型設計接口 導致的參數類型不匹配問題
問題描述
1.設計了一個接口用于包裝其它 pojo,以計算是否過期
public interface CatchWrapper<T>{ public long getCatchedTime();public T getValue();public boolean valid();}
某一個實現:
public class DeviceCatchWrapper implements CatchWrapper<Device> { private final long catchedTime; private final Device device; private static final long CATCH_TIME = 20*1000; public DeviceCatchWrapper(Device device) {this.device = device;catchedTime = System.currentTimeMillis(); } @Override public long getCatchedTime() {return catchedTime; } @Override public Device getValue() {return device; } @Override public boolean valid() {return System.currentTimeMillis() - catchedTime < CATCH_TIME; }}
另有一個管理類,主要是刪除過期的緩存
public class DeviceCatchWrapperManager<T> { private static final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private final ConcurrentMap<String, CatchWrapper<T>> catchStore; private final long initialDelay; private final long delay; private TimeUnit unit; private volatile boolean stop = false; public DeviceCatchWrapperManager(ConcurrentMap<String,CatchWrapper<T>> catchStore, long initialDelay, long delay, TimeUnit unit) {this.catchStore = catchStore;this.initialDelay = initialDelay;this.delay = delay;this.unit = unit; } /** * 周期性檢查過期的緩存,然后刪除 */ public void startLoop() {service.scheduleWithFixedDelay(new Runnable() { @Override public void run() {for (Entry<String, CatchWrapper<T>> entry : catchStore.entrySet()) { if (stop)break; String key = entry.getKey(); CatchWrapper<T> cw = entry.getValue(); if (!cw.valid()){System.out.println('Device catch manager --------------->remove:'+key);catchStore.remove(key, cw); }} }}, initialDelay, delay, unit); } /** * 停在對緩存進行過期檢查 */ public void stop() {stop = true;service.shutdownNow(); }}
但是真正構造函數 傳參數報錯
private final ConcurrentMap<String, DeviceCatchWrapper> catchMap = new ConcurrentHashMap<>(); 下面的報錯,參數不對private final DeviceCatchWrapperManager<Device> catchManager = new DeviceCatchWrapperManager<Device>(catchMap, 2, 2, TimeUnit.HOURS);
改怎么解決這個錯誤 或者 該怎么設計接口或者改進呢?
問題解答
回答1:ConcurrentMap<String, DeviceCatchWrapper> catchMap = new ConcurrentHashMap<>(); 這句有問題改成ConcurrentMap<String, CatchWrapper<Device>> catchMap = new ConcurrentHashMap<String, DeviceCatchWrapper>();試試
相關文章:
1. javascript - 微信小程序里怎么把頁面轉成圖片分享2. python3.x - Python中出現AttributeError: object has no attribute3. python把第x列數據寫入第x個文件4. python 多進程 或者 多線程下如何高效的同步數據?5. 微信端電子書翻頁效果6. mysql - 我用SQL語句 更新 行的時候,發現全部 中文都被清空了,請問怎么解決?7. mysql - SQL問個基礎例子,書上的,我怎么看都看不懂..誰幫我解釋一下第2個為什么和第1個一樣?8. 數據庫 - mysql boolean型無法插入true9. python - flask_Bootstrap的WTF的調用疑問10. mysql服務無法啟動1067錯誤,誰知道正確的解決方法?
