简体   繁体   English

Kotlin推断Java类上的属性不遵循正常的getter / setter约定?

[英]Kotlin Infer Properties on Java Classes that do not follow normal getter/setter conventions?

I'm looking to create a Kotlin wrapper around a Java library with some poor design decisions. 我正在寻找围绕Java库创建Kotlin包装器的设计决策。 One problem I'm facing is none of the POJOs in the library follow normal Java Bean conventions for getters and setter. 我面临的一个问题是,库中的POJO都不遵循用于getter和setter的常规Java Bean约定。

Kotlin can infer properties on Java objects that follow normal getter/setter conventions: Kotlin可以推断遵循正常的getter / setter约定的Java对象的属性:

Methods that follow the Java conventions for getters and setters (no-argument methods with names starting with get and single-argument methods with names starting with set) are represented as properties in Kotlin. 遵循getter和setter的Java约定的方法(名称以get开头的无参数方法和名称以set开头的单参数方法)在Kotlin中表示为属性。 Boolean accessor methods (where the name of the getter starts with is and the name of the setter starts with set) are represented as properties which have the same name as the getter method. 布尔访问器方法(getter的名称以is开头,setter的名称以set开头)表示为与getter方法具有相同名称的属性。

(See here ) (请参阅此处

But in the case of this library all the POJOs have getters and setters that are just the name of the field rather than getField/setField so Kotlin can not infer the properties access syntax. 但是在该库的情况下,所有POJO都具有getter和setter,它们只是字段的名称,而不是getField / setField,因此Kotlin无法推断属性访问语法。

What would be the cleanest way to wrap these objects and use normal Kotlin conventions? 包装这些对象并使用常规Kotlin约定的最干净方法是什么?

It seems like implementing proper getters and setters with extension methods does not enable property access syntax (I'm guessing this is because under the hood extension methods are turned into static utility classes and the extended class is not actually modified). 似乎使用扩展方法实现正确的getter和setter方法无法启用属性访问语法(我猜这是因为在内部,扩展方法已转换为静态实用程序类,而扩展类并未实际修改)。

What alternatives are available? 有哪些替代选择?

You can make extension properties, just like extension methods. 您可以像扩展方法一样设置扩展属性

val Foo.bar: Bar
  get() = someOtherWayOfGettingBar()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM