我大致有这些类型:
interface Record {}
interface UpdatableRecord extends Record {}
interface Insert<R extends Record> {
// Calling this method only makes sense if <R extends UpdatableRecord>
void onDuplicateKeyUpdate();
}
我想<R>
在调用时有一个额外的限制onDuplicateKeyUpdate()
。<R>
这样做的原因是,这种方法只有在绑定到 的任何子类型时才有意义,UpdatableRecord
而不仅仅是Record
. 例子:
Insert<?> i1;
Insert<Record> i2;
Insert<UpdatableRecord> i3;
// these shouldn't compile
i1.onDuplicateKeyUpdate();
i2.onDuplicateKeyUpdate();
// this should compile
i3.onDuplicateKeyUpdate();
有没有什么技巧或方法可以用来为类的泛型类型添加一个额外的限制,只是为了一个方法声明?
注意:
- 声明
Insert<R extends UpdatableRecord>
不是一种选择,因为我希望拥有Insert<R extends Record>
不可更新的记录的灵活性 - 推导
UpdatableInsert<R extends UpdatableRecord> extends Insert<R>
该方法并将其向下推可能是一种选择,但我真的不想引入一种新类型。我有几个这样的方法有几个不同的限制,这会导致类型爆炸。 - 投掷
UnsupportedOperationException
是相当明显的,但它似乎是 Java 1.4 的做法。我真的想知道我是否可以使用泛型和编译器来解决这个问题。
理想的解决方案:
// This would be an annotation to be interpreted by the compiler. There is no such
// thing in Java, as far as I know. But maybe there's a trick having the same effect?
@Require(R extends UpdatableRecord)
void onDuplicateKeyUpdate();