关于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. python - Pycharm调试代码进行列表遍历时,如何直接赋值指定元素2. atom编译器 如何格式化前端代码文件?3. angular.js - Angular1使用bootstrap轮播条carousel不能自动轮播4. python - 基于scrapy-redis的分布式爬虫运行的时候不能正常运行 遇到的问题如下截图所示5. css3 - 我的css用less写的,eclipse的jsp文件要修改css很麻烦,怎么解决?6. android - 新建项目卡在Gradle:Resolvedependencies’:app:_debugCompile’7. javascript - webpack热加载配置不生效8. angular.js - ng-repeat的数据排序,我用了orderBy: d.supportNum为什么失效?9. Android Studio 中程序添加不上Xutils 3.0 jar包10. javascript - 关于在angularjs的select中遇到的问题!!