我有一个类型,MyType<T>,它包含一个泛型类型T。我有一个BlockingQueue<MyType<T>>类型的阻塞队列。我想向队列发送“终止流”标记,即毒丸,但问题是,由于一般类型,我无法实例化毒丸。有办法绕道吗?
发布于 2015-07-13 13:33:52
你应该能创造一个。
class MyType<T> {
private BlockingQueue<MyType<T>> q = new ArrayBlockingQueue<>(10);
// Poison pill to signal the end of the queue.
public static final MyType<?> PILL = new MyType<>();
/**
* Special private constructor for PILL creation.
*/
private MyType() {
}
public boolean queueClosed() {
return q.peek() == PILL;
}
}如果您有自己的构造函数,则可以添加没有参数的private构造函数。
发布于 2015-07-13 13:36:12
您仍然可以创建泛型对象并直接转换它。例如,查看java.util.Collections.emptyList():
@SuppressWarnings("unchecked")
public static final List EMPTY_LIST = new EmptyList<Object>();
@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}只需确保流结束标记处理不使用/不依赖
发布于 2015-07-13 13:33:32
如果没有看到代码,就很难找到正确的解决方案。我能想到的是:
MyType添加一种方法,表明这是一种毒丸。PoisonPill标记接口,并向MyType添加一个getPoison()静态方法,该方法返回一个MyType implements PoisonPill,然后使用instanceof进行测试。https://stackoverflow.com/questions/31384529
复制相似问题