gpt4 book ai didi

java - Kotlin 反射与 Java 的互操作性

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:45:20 27 4
gpt4 key购买 nike

开发人员在编写同时适用于 Java 和 Kotlin 的反射代码时应注意哪些注意事项?

例如,我有一个使用反射的现有库,它与 Java 配合得很好。但是,当我将其与 Kotlin 一起使用时,我的反射代码似乎没有提取字段上的注释。

以下是我注意到的一些差异。

<强>1。获取类实例

// Example 1.1 - Java
Class<?> userClass = User.class; // From a class name
userClass = userInstance.getClass(); // OR from an instance

在 Kotlin 中获取 Java 类实例

// Example 1.2 - Kotlin
val userClass = userInstance.javaClass // From an instance

我无法像在 Java 中那样在 Kotlin 中使用 .class 工具或 .getClass() 方法。

<强>2。代表们

当我在 Kotlin 类中使用委托(delegate)属性时,我检索的属性具有 $delegate 后缀。这与我们在 Java 中获得的字段有点相反(我确实理解 Kotlin 没有字段,只有属性)。这对元编程有何影响?

但是,对于委托(delegate),我发现大多数方法都保留了它们在 Java 中的行为。还有其他我必须注意的区别吗?

让 Java 和 Kotlin 对我来说可以互操作需要了解上面讨论的 1,以及 Kotlin 给元编程带来的其他限制/差异。

最佳答案

For example, I have an existing library that uses reflection and it works well with Java. However, when I use the same with Kotlin, my reflective code doesn't seem to pick up the annotations on fields.

会不会是因为字段现在是私有(private)的?

无论如何,目前字段上的注释存在问题,这将在即将到来的里程碑中修复。

其他一些相关问题:

I'm unable to use the .class facility or the .getClass() method in Kotlin as we do in Java.

只有语法不同:javaClass<C>()C.class 完全一样, 和 x.javaClassx.getClass() 做同样的事情

When I use delegated properties in a Kotlin class, the properties that I retrieve have the $delegate suffix.

小更正:字段$delegate后缀,而不是属性。

However, with delegates I see that most of the methods retain their behavior as they do in Java. Are there any other differences that I have to be aware of?

文档 here给你详细描述委托(delegate)属性是如何实现的。

Making Java and Kotlin interoperable for me would require understanding about 1 discussed above, plus other limitations / differences that Kotlin brings to meta-programming.

您的 Kotlin 代码越像 Java 代码,从反射的角度来看差异就越小。如果您编写惯用的 Kotlin,例如使用默认参数值、特征、属性、委托(delegate)、顶级函数、扩展等,您获得的类与惯用的 Java 不同,否则它们是紧密对齐的。

关于java - Kotlin 反射与 Java 的互操作性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28190962/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com