如何在接口中为属性指定@Throws [英] How to specify @Throws for a property in interface

查看:157
本文介绍了如何在接口中为属性指定@Throws的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将一些Java RMI代码移植到Kotlin. Java的旧界面是:

I am currently porting some Java RMI code to Kotlin. The legacy interface in Java is:

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

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

After running the auto-migration tool, the field bar is changed into a property:

interface Foo: Remote {
    val bar: Bar
}

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

However, in the migrated program, getBar is no longer marked as throws RemoteException, which causes illegal remote method encountered error in a RMI call.

我想知道是否有任何方法可以将@Throws标记为财产?

I was wondering is there any way to mark @Throws for a property?

推荐答案

好吧,如果您查看

Well, if you look at @Throws:

如果存在不使用背景字段的特定吸气剂,只需直接对其进行批注:

If there is a specific getter that does not use the backing field, simply annotate it directly:

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

@Throws的有效目标是

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

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

So in other cases, you need to target the getter itself and not the property:

@get:Throws(RemoteException::class)

支持的使用场所目标的完整列表是:

  • 文件;
  • 属性(带有此目标的注释对Java不可见);
  • field;
  • 获取(属性获取器);
  • 设置(属性设置器);
  • 接收器(扩展功能或属性的接收器参数);
  • param(构造函数参数);
  • setparam(属性设置器参数);
  • delegate(存储委托属性的委托实例的字段).
  • 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指定将此注释应用于吸气剂.

@get specifies that this annotation will be applied to the getter.

您的完整界面将会是

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

但这是一个问题-在生成的代码中,没有 生成throws子句.我觉得这可能是一个错误,因为注释已明确标记为针对这四个使用地点. CONSTRUCTORFUNCTION绝对有效,只是没有生成的属性.

Here's a problem though - in the generated code, there is no throws clause generated. I feel like this may be a bug, as the annotation is clearly marked as targeting these four use-sites. CONSTRUCTOR and FUNCTION definitely work, it's just the property ones that have none generated.

我看了一下Kotlin编译器,试图找到可能的原因,然后发现

I took a look at the Kotlin compiler trying to find a possible reason, and I found this:

interface ReplStateFacade : Remote {

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

    ...
}

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

Which interestingly avoids properties in order to use @Throws. Maybe this is a known workaround?

这篇关于如何在接口中为属性指定@Throws的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆