Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active August 21, 2017 07:23
Show Gist options
  • Save pokk/dc920b9e2493798125f2783a9dba0287 to your computer and use it in GitHub Desktop.
Save pokk/dc920b9e2493798125f2783a9dba0287 to your computer and use it in GitHub Desktop.
Create an object from generic parameter in the class.
// There is a class with generic parameter.
abstract class A<T> {
// This is KClass version.
val t: T by lazy {
(this@A::class
.supertypes.first() // KType of A class
.arguments.first() // Data type of the generic T
.type!!.classifier as KClass<*>) // The class of the generic T
.primaryConstructor!!.call() as T // An object from the generic T
}
// This is java Class version.
val j: T by lazy {
((this::class.java
.genericSuperclass as ParameterizedType)
.actualTypeArguments[0] as Class<*>)
.getConstructor().newInstance() as T
}
}
class B extends A<C>()
class C {
void String test()
{
return "the test code of object C";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment