实现不安全的 Java 接口
最近在使用 Spring Security 进行开发时遇到了一个问题。它有一个具有以下签名的接口 GrantedAuthority
:
public interface GrantedAuthority extends Serializable, Comparable
对于 Java 1.5 及更高版本,接口 Comparable
采用类型参数 T
,该参数被省略在 Spring Security 库中(显然,是为了兼容 JVM 1.4)。
所以我尝试在 Scala 中实现 GrantedAuthority
。
class Role extends GrantedAuthority {
. . .
def compareTo(obj: Any): Int = obj match {
case (r: Role) => r.toString.compareTo(this.toString)
case _ => -1
}
}
它无法编译:
error: class Role needs to be abstract, since method compareTo in trait Comparable of type (T)Int is not defined
如何在 Scala 中实现这样的接口?
I've ran into a problem recently while developing with Spring Security. It has an interface GrantedAuthority
with following signature:
public interface GrantedAuthority extends Serializable, Comparable
And as for Java 1.5 and later, the interface Comparable
takes a type parameter T
, which is omitted in Spring Security libraries (obviously, for JVM 1.4 compatibility).
So I am trying to implement GrantedAuthority
in Scala.
class Role extends GrantedAuthority {
. . .
def compareTo(obj: Any): Int = obj match {
case (r: Role) => r.toString.compareTo(this.toString)
case _ => -1
}
}
It does not compile:
error: class Role needs to be abstract, since method compareTo in trait Comparable of type (T)Int is not defined
How can I implement such interface in Scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Java 泛型的互操作问题(至少)有两种形式:
Comparable
被视为存在类型Comparable[_]
。有时你可以想办法摆脱这个问题。但是,在这种情况下,我没有找到实现 defcompareTo(other: _) = ... 的方法。Ordering[-T]
扩展Comparable[T]
,将会发生错误,除非您使用@uncheckedVariance
注释。 (讨论邮件列表)我建议您尝试升级到 Spring 3.x,它是针对 Java 1.5 编译的。如果这不可能,请在 Java 中编写一个基类
BaseGrantedAuthority
,它实现compareTo
并委托给可以在 Scala 中实现的模板方法。Interop problems with Java Generics come in (at least) two forms:
Comparable
is treated as the existential typeComparable[_]
. Sometimes you can cast your way out of this problem. However, I don't see a way to implementdef compareTo(other: _) = ...
in this case.Comparable[T]
with a contravariant scala traitOrdering[-T]
an error would occur unless you use the@uncheckedVariance
annotation. (Discussion on the mailing list)I suggest you try to upgrade to Spring 3.x which is compiled against Java 1.5. If this is not possible, write a base class
BaseGrantedAuthority
in Java that implementscompareTo
and delegates to a template method that can implemented in Scala.