Hi, how can I access a generic type T for a class ...
# announcements
j
Hi, how can I access a generic type T for a class ?
Copy code
abstract class TestCase<T : Activity>() {
    val classz = (javaClass
            .genericSuperclass as ParameterizedType).getActualTypeArguments()[0] as Class<T>
    @Rule
    @JvmField
    val rule = IntentsTestRule(classz, false, false)
	}
This seems to work to
open FooTestCase: TestCase<ActivityA>
, but not to
BarTestCase: FooTestCase
...
a
what exactly doesn't work?
d
You need to walk up the superclass tree until you find the
TestCase
class and then grab the
genericSuperclass
for that.
j
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
d
Because the superclass of
BarTestCase
is
FooTestCase
, which is not parameterized
j
Is there a generic way to get that T value?
d
You have to loop until you find the class you need.
You could use Guava's TypeToken for an existing implementation.
j
ok, I thought maybe Kotlin could have something to make it easier. Thanks