Last active
August 21, 2017 07:23
-
-
Save pokk/dc920b9e2493798125f2783a9dba0287 to your computer and use it in GitHub Desktop.
Create an object from generic parameter in the class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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