Java/Kotlin utility to infer actual type for inherited type parameters
If you have a class hierarchy where base class has type parameters, and you need to access actual type defined in inherited class you may pass it to constructor or defined an abstract method for that.
abstract class Dao<E: Any> {
abstract val entityType: Class<E>
fun getTypeName() = entityType.name
}
class UserDao<User>: Dao<User>() {
override val entityType = User::class.java
}
class GroupDao<Group>: Dao<Group>() {
override val entityType = Group::class.java
}
But information about the type variable value for the class UserDao
is actually available. You can get
it using the method inferTypeParameter
from the library.
abstract class Dao<E: Any> {
open val entityType: Class<E> = inferTypeParameterClass(Dao::class.java, "E", javaClass)
fun getTypeName() = entityType.name
}
class UserDao<User>: Dao<User>()
class GroupDao<Group>: Dao<Group>()
open class Figure<A> {
open fun compare(that: A, p: String, i: Int) = false
}
class Rectangle<B> : Figure<B>() {
override fun compare(that: B, o: String, i: Int) = true
}
fun check() {
Rectangle<*>::compare.isOverriding(Figure<*>::compare) // true
}
repositories {
mavenCentral()
}
dependencies {
compile 'com.github.mazine:infer-hierarchy-type-parameter:$version'
}
<dependency>
<groupId>com.github.mazine</groupId>
<artifactId>infer-hierarchy-type-parameter</artifactId>
<version>$version</version>
</dependency>