ysny.karibu-tools.karibu-tools.0.20.source-code.MiscUtils.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of karibu-tools Show documentation
Show all versions of karibu-tools Show documentation
Karibu-Tools: The Vaadin Missing Utilities
package com.github.mvysny.kaributools
import elemental.json.JsonNull
import elemental.json.JsonValue
import java.beans.Introspector
import java.beans.PropertyDescriptor
import java.lang.reflect.Method
import kotlin.reflect.KProperty1
internal fun String.containsWhitespace(): Boolean = any { it.isWhitespace() }
private val regexWhitespace = Regex("\\s+")
internal fun String.splitByWhitespaces(): List = split(regexWhitespace).filterNot { it.isBlank() }
/**
* Returns the getter method for given property name; fails if there is no such getter.
*/
public fun Class<*>.getGetter(propertyName: String): Method {
val descriptors: Array = Introspector.getBeanInfo(this).propertyDescriptors
val descriptor: PropertyDescriptor? = descriptors.firstOrNull { it.name == propertyName }
requireNotNull(descriptor) { "No such field '$propertyName' in $this; available properties: ${descriptors.joinToString { it.name }}" }
val getter: Method = requireNotNull(descriptor.readMethod) { "The $this.$propertyName property does not have a getter: $descriptor" }
return getter
}
/**
* Returns a [Comparator] which compares beans of type [T] by values of a property
* identified by given [propertyName].
*/
public fun Class.getPropertyComparator(propertyName: String): Comparator {
val getter: Method = getGetter(propertyName)
return compareBy { if (it == null) null else getter.invoke(it) as Comparable<*> }
}
/**
* Returns a [Comparator] which compares beans of type [T] by values of given property.
*/
public inline val KProperty1.comparator: Comparator
get() = T::class.java.getPropertyComparator(name)
/**
* Checks whether `this` is either null or [JsonNull].
*/
public val JsonValue?.isNull: Boolean
get() = this == null || this is JsonNull