我@JvmSynthetic在kotlin-stdlib中遇到了注释,我想知道它是什么,但不幸的是,它没有记录.
据我所知,将它应用于程序元素会将synthetic修饰符添加到相应的字节码元素.结果,该元素从Java变得不可见:
class MyClass {
@JvmSynthetic
fun f() { }
}
Run Code Online (Sandbox Code Playgroud)
Java代码中的某处:
MyClass c = new MyClass();
c.f() // Error: cannot resolve method f()
Run Code Online (Sandbox Code Playgroud)
但是在Kotlin代码中仍然可以看到相同的元素:
val c = MyClass()
c.f() // OK
Run Code Online (Sandbox Code Playgroud)
隐藏来自非Kotlin来源的声明是否有效使用@JvmSynthetic?它是预期用途吗?其他适当的用例是什么?
由于@JvmSynthetic隐藏了来自Java的函数,它们也无法在Java中被覆盖(当涉及abstract成员时,调用会产生AbstractMethodError).鉴于此,我可以@JvmSynthetic用来禁止在Java源代码中覆盖Kotlin类的成员吗?
我正在为一个库编写一个DSL,我想使用这样的具体类型参数提供类型元数据:
val config = Config.create()
.consumerFor<MyType>{
// consume
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我只能reified在inline函数和函数中使用关键字inline我不能使用像这样的实例字段:
inline fun <reified T> consumerFor(consumer: (T) -> Unit) {
consumers.put(T::class.java, consumer)
return this
}
Run Code Online (Sandbox Code Playgroud)
因为我收到一个错误:
Public-API内联函数无法访问非公共API的私有最终val消费者...
到目前为止,我似乎无法使用最有用的reified类型参数.这有解决方法吗?
我想要一些方法只对kotlin代码可见,而不是Java代码.
例如,这里的方法fun method(){}只能在kotlin代码中调用,不能在Java代码中调用.
我有一个泛型函数,需要实例化其泛型参数的对象并将其传递给某个接口的实例。
据我所知,实例化通用对象的唯一方法是使函数内联并具体化该类型参数。但我不想公开该接口的实现。
问题是内联函数不能使用内部类。
我基本上想要的是这样的:
/* The interface I want to expose */
interface Params<T> {
val doc: T
}
/* The implementation I do not want to expose */
internal class ParamsImpl<T> (override val doc: T) : Params<T>
/* The function */
inline fun <reified T> doSomething(init: Params<T>.() -> Unit) {
val doc= T::class.java.newInstance()
val params = ParamsImpl(doc) // Can't compile since ParamsImpl is internal
params.init()
}
Run Code Online (Sandbox Code Playgroud) kotlin ×4
java ×3
generics ×1
inline ×1
java-interop ×1
reification ×1
synthetic ×1
visible ×1