我目前正在将一些 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
子句。我觉得这可能是一个错误,因为注释清楚地标记为针对这四个使用站点。 CONSTRUCTOR
和 FUNCTION
确实有效,它只是没有生成的属性。
我查看了 Kotlin 编译器,试图找出可能的原因,我找到了 this :
interface ReplStateFacade : Remote {
@Throws(RemoteException::class)
fun getId(): Int
...
}
有趣的是为了使用 @Throws
而避免了属性。
也许这是一个已知的解决方法?
关于java - 如何为接口(interface)中的属性指定@Throws,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47737288/