/* Convenience wrapper that allows you to call getValue<Type>() instead of of getValue(Type::class) */
inline fun <reified T: Any> getValue() : T? = getValue(T::class)
/* We have no way to guarantee that an empty constructor exists, so must return T? instead of T */
fun <T: Any> getValue(clazz: KClass<T>) : T? {
clazz.constructors.forEach { con ->
if (con.parameters.size == 0) {
return con.call()
}
}
return null
}
如果我们添加一些示例类,您可以看到这将在空构造函数存在时返回实例,否则返回null:
class Foo() {}
class Bar(val label: String) { constructor() : this("bar")}
class Baz(val label: String)
fun main(args: Array<String>) {
System.out.println("Foo: ${getValue<Foo>()}") // [email protected]
// No need to specify the type when it can be inferred
val foo : Foo? = getValue()
System.out.println("Foo: ${foo}") // [email protected]
System.out.println("Bar: ${getValue<Bar>()}") // Prints [email protected]
System.out.println("Baz: ${getValue<Baz>()}") // null
}
1 回答
编辑:正如评论中提到的,这可能是一个坏主意 . 接受
() -> T
可能是实现这一目标的最合理方式 . 也就是说,以下技术将实现您正在寻找的东西,如果不一定是最惯用的方式 .不幸的是,你无法直接实现这一点:Kotlin因其Java系统而受到限制,因此泛型会在运行时被删除,这意味着T不再可以直接使用 . 使用反射和内联函数,您可以解决此问题:
如果我们添加一些示例类,您可以看到这将在空构造函数存在时返回实例,否则返回null: