实现不安全的 Java 接口

发布于 2024-08-20 23:27:24 字数 743 浏览 3 评论 0原文

最近在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁把谁当真 2024-08-27 23:27:24

Java 泛型的互操作问题(至少)有两种形式:

  1. 省略类型参数的 Java 代码(如您的示例中所示)会导致“原始类型”。 Comparable 被视为存在类型 Comparable[_]。有时你可以想办法摆脱这个问题。但是,在这种情况下,我没有找到实现 defcompareTo(other: _) = ... 的方法。
  2. Java 泛型没有声明位点差异的概念。要使用逆变 scala 特征 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:

  1. Java code that omits type arguments, as in your example, leads to 'raw types'. Comparable is treated as the existential type Comparable[_]. Sometimes you can cast your way out of this problem. However, I don't see a way to implement def compareTo(other: _) = ... in this case.
  2. Java generics don't have a notion of declaration site variance. To extend Comparable[T] with a contravariant scala trait Ordering[-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 implements compareTo and delegates to a template method that can implemented in Scala.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文