如何为接口中的属性指定@Throws
我目前正在将一些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
的财产?
那么,如果你看@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)
支持的使用站点目标的完整列表是:
- 文件;
- 属性(对此目标的注释对于Java不可见);
- 领域;
- 得到(财产获得者);
- 设置(property setter);
- 接收器(扩展函数或属性的接收器参数);
- param(构造函数参数);
- setparam(属性设置参数);
- 委托(存储委托属性的委托实例的字段)。
@get
指定这个注解将被应用到getter。
你的完整界面将是
interface Foo: Remote { @get:Throws(RemoteException::class) val bar: Bar }
这是一个问题,但在生成的代码中,没有生成throws
子句。 我觉得这可能是一个错误,因为注释明确标记为针对这四个使用地点。 CONSTRUCTOR
和FUNCTION
绝对有效,只是属性没有产生。
我看了Kotlin编译器试图find一个可能的原因,我发现这个 :
interface ReplStateFacade : Remote { @Throws(RemoteException::class) fun getId(): Int ... }
其中有趣的是避免使用@Throws
属性。 也许这是一个已知的解决方法?