java - 如何为接口(interface)中的属性指定@Throws

标签 java kotlin rmi

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

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

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

interface Foo: Remote {
    val bar: Bar
}

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

我想知道有什么方法可以为属性标记 @Throws 吗?

最佳答案

好吧,如果你看看@Throws :

如果有特定的getter不使用backing field,直接注释即可:

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 is:

  • file;
  • property (annotations with this target are not visible to Java);
  • field;
  • get (property getter);
  • set (property setter);
  • receiver (receiver parameter of an extension function or property);
  • param (constructor parameter);
  • setparam (property setter parameter);
  • delegate (the field storing the delegate instance for a delegated property).

@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 而避免了属性。 也许这是一个已知的解决方法?

关于java - 如何为接口(interface)中的属性指定@Throws,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47737288/

相关文章:

java - 如何在 Mockito 中 stub 可变参数以仅匹配一个参数

android - 在 Admob 20.1.0 中永远不会调用 onUserEarnedReward

java - RMI 远程对象到 stub

Java,添加变量时 while 循环崩溃 --> 白色,无响应的 JFrame

java - Android/华为 : java. io.FileNotFoundException :/data/cust/xml/hw_launcher_load_icon. xml: 打开失败: ENOENT (没有这样的文件或目录)

java - 如何使用 eclipselink 在基于多模式的 Multi-Tenancy Web 应用程序中添加缺失的列

java - Class.forName ("FQN") 间歇性抛出 ClassNotFoundException

java - 如何测试PreparedStatement是否会耗尽内存

android - java.io.IOException : Cannot run program CreateProcess error=2, 系统找不到android studio上指定的文件

java - 让 2 个 Tomcat 服务器相互通信