I've seen similar questions but they didnt help very much.
For instance I've got this Generic Class:
public class ContainerTest<T> { public void doSomething() { //I want here to determinate the Class of the type argument (In this case String) } }
and Another Class which uses this Container Class
public class TestCase { private ContainerTest<String> containerTest; public void someMethod() { containerTest.doSomething(); } }
Is it possible to determinate the Class of the type argument in method doSomething() without having an explicit type variable/field or any constructor in ContainerTest Class?
Update: Changed format of ContainerTest Class
Pass the class object instead and it's easy. The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter. Show activity on this post. Show activity on this post.
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
Use getClass(). getSimpleName() to Check the Type of a Variable in Java. We can check the type of a variable in Java by calling getClass(). getSimpleName() method via the variable.
Generic Classes These classes are known as parameterized classes or parameterized types because they accept one or more parameters.
The only way is to store the class in an instance variable and require it as an argument of the constructor:
public class ContainerTest<T> { private Class<T> tClass; public ContainerTest(Class<T> tClass) { this.tCLass = tClass; } public void doSomething() { //access tClass here } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With