在看的同时这个问题 https://stackoverflow.com/q/47737288/7366707,我注意到申请@Throws
to a get
or set
use-site 没有影响。
此外,唯一有效的目标 for @Throws
are AnnotationTarget.FUNCTION
, AnnotationTarget.PROPERTY_GETTER
, AnnotationTarget.PROPERTY_SETTER
, and AnnotationTarget.CONSTRUCTOR
.
其他注释,例如 JPA 注释和Deprecated
工作正常并正确应用该方法!
这是奇怪的行为。
为了进行演示,我用 Java 创建了一个简单的抽象类,其中包含一个构造函数、一个方法和一个 get 方法。
public abstract class JavaAbstractClass {
@Deprecated
@NotNull public abstract String getString() throws IOException;
public abstract void setString(@NotNull String string) throws IOException;
public abstract void throwsFunction() throws IOException;
public JavaAbstractClass() throws IOException {
}
}
如您所见,每个方法/构造函数都被标记为抛出IOException
.
然而,当我尝试在 Kotlin 中编写一个等效的类,并用throws
对于互操作,生成的getString
and setString
方法没有throws
clause.
abstract class KotlinAbstractClass @Throws(IOException::class) constructor() {
@get:Deprecated("Deprecated")
@get:Throws(IOException::class)
@set:Throws(IOException::class)
abstract var string: String
@Throws(IOException::class)
abstract fun throwsFunction()
}
反编译后的代码:
@Metadata(Some metadata here)
public abstract class KotlinAbstractClass {
/** @deprecated */
@Deprecated(
message = "Deprecated"
) // @Deprecated made it through!
@NotNull
public abstract String getString(); // Nothing here!
public abstract void setString(@NotNull String var1); // Nothing here!
public abstract void throwsFunction() throws IOException;
public KotlinAbstractClass() throws IOException {
}
}
对我来说,这似乎是因为这些内部注释必须由编译器专门处理,而不是直接应用于方法。
此外,将其应用于非抽象属性的 getter:
val string: String
@Throws(IOException::class) get() = "Foo"
does生成带有签名的方法public final String getString() throws IOException
!
也许这个案子处理得不好?
这是一个错误吗?
注意:这与该方法是否实际抛出此异常没有任何关系。
If I do:
@get:Throws(IOException::class)
val string: String
get() = BufferedReader(FileReader("file.txt")).readText()
编译后的代码依然是
@NotNull
public final String getString() {
return TextStreamsKt.readText((Reader)(new BufferedReader((Reader)(new FileReader("file.txt")))));
}
尽管事实上FileReader构造函数 https://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html#FileReader(java.io.File)抛出一个FileNotFoundException
.
此外,无论如何,这对于抽象方法来说并不重要,因为它们不能有实现,但仍然可以有一个throws
clause.
如果我这样做@tynn https://stackoverflow.com/users/3385212/tynn建议并添加具体实现:
class ConcreteClass : KotlinAbstractClass() {
override val string: String
get() = BufferedReader(FileReader("file.txt")).readText()
...
}
我仍然得到相同的结果。