我大致有这些类型:
interface Record {}
interface UpdatableRecord extends Record {}
interface Insert {
// Calling this method only makes sense if
void onDuplicateKeyUpdate();
}
我想对< R>进行额外的限制.调用onDuplicateKeyUpdate()时.其原因在于,当< R>时,该方法才有意义.绑定到UpdatableRecord的任何子类型,而不仅仅是Record.例子:
Insert> i1;
Insert i2;
Insert i3;
// these shouldn't compile
i1.onDuplicateKeyUpdate();
i2.onDuplicateKeyUpdate();
// this should compile
i3.onDuplicateKeyUpdate();
是否有任何技巧或方法可以用于为一个方法声明添加类’泛型类型的附加限制?
注意:
>声明插入< R extends UpdatableRecord>不是一个选项,因为我想要一个Insert< R extends Record>的灵活性.对于不可更新的记录
>派生UpdatableInsert< R扩展UpdatableRecord>扩展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();