如何为接口中的属性指定@Throws

时间:2017-12-10 08:54:03

标签: java kotlin rmi

我目前正在将一些Java RMI代码移植到Kotlin。 Java中的遗留接口是:

interface Foo: Remote {
    Bar getBar() throws RemoteException
}

运行自动迁移工具后,字段bar将更改为属性:

interface Foo: Remote {
    val bar: Bar
}

但是,在迁移的程序中,getBar不再标记为throws RemoteException,这会导致RMI调用中出现illegal remote method encountered错误。

我想知道有没有办法将@Throws标记为某个属性?

1 个答案:

答案 0 :(得分:4)

好吧,如果你看一下@Throws

如果有一个特定的getter不使用支持字段,只需直接注释:

val bar: Bar
    @Throws(RemoteException::class) get() = doSomething()

@Throws的有效目标是

AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.CONSTRUCTOR

因此,在其他情况下,您需要定位getter本身而不是属性:

@get:Throws(RemoteException::class)
  

The full list of supported use-site targets是:

     
      
  • 文件;
  •   
  • 属性(具有此目标的注释对Java不可见);
  •   
  • 字段;
  •   
  • get(property getter);
  •   
  • set(property setter);
  •   
  • 接收器(扩展功能或属性的接收器参数);
  •   
  • param(构造函数参数);
  •   
  • setparam(属性设置器参数);
  •   
  • delegate(存储委托属性的委托实例的字段)。
  •   

@get指定此注释将应用于getter。

您的完整界面将是

interface Foo: Remote {
    @get:Throws(RemoteException::class)
    val bar: Bar
}

这是一个问题 - 在生成的代码中,没有生成throws子句。我觉得这可能是一个错误,因为注释明确标记为针对这四个使用网站。 CONSTRUCTORFUNCTION肯定有用,它只是没有生成的属性。

我看了一下Kotlin编译器试图找到一个可能的原因,我找到了this

interface ReplStateFacade : Remote {

    @Throws(RemoteException::class)
    fun getId(): Int

    ...
}

为了使用@Throws,有趣地避免使用属性。 也许这是一个已知的解决方法?

相关问题