All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ysny.karibu-tools.karibu-tools.0.20.source-code.MiscUtils.kt Maven / Gradle / Ivy

There is a newer version: 0.21
Show newest version
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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy