https://kotlinlang.org logo
Title
j

juliocbcotta

05/14/2018, 2:57 PM
Hi, how can I access a generic type T for a class ?
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

Andreas Sinz

05/14/2018, 2:58 PM
what exactly doesn't work?
d

diesieben07

05/14/2018, 2:58 PM
You need to walk up the superclass tree until you find the
TestCase
class and then grab the
genericSuperclass
for that.
j

juliocbcotta

05/14/2018, 2:58 PM
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
d

diesieben07

05/14/2018, 2:58 PM
Because the superclass of
BarTestCase
is
FooTestCase
, which is not parameterized
j

juliocbcotta

05/14/2018, 2:58 PM
Is there a generic way to get that T value?
d

diesieben07

05/14/2018, 2:59 PM
You have to loop until you find the class you need.
You could use Guava's TypeToken for an existing implementation.
j

juliocbcotta

05/14/2018, 3:00 PM
ok, I thought maybe Kotlin could have something to make it easier. Thanks