简体   繁体   中英

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. One problem I'm facing is none of the POJOs in the library follow normal Java Bean conventions for getters and setter.

Kotlin can infer properties on Java objects that follow normal getter/setter conventions:

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. 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.

(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.

What would be the cleanest way to wrap these objects and use normal Kotlin conventions?

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).

What alternatives are available?

You can make extension properties, just like extension methods.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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