21
In the following class I want to assign the attribute clazz
class type inferring it from the list given in the constructor.
class Foo<T> {
private Class<T> clazz;
Foo(List<T> list) {
//this.clazz = tipo da classe inferido a partir da lista
}
...
}
My first attempt was to use the method list.getClass()
which proved to be wrong, because the value returned by the method was java.util.ArrayList
.
How to infer the type of a bean informed in an Arraylist? It is possible to make this type of inference from the parameter, as in the example? If yes, how it would be? If not, which possibilities exist, or how to adjust this class so as to assign the correct value to the attribute clazz
?
This question is exactly the same as on the Soen: http://stackoverflow.com/q/3403909/2766598
– Delfino
Hello, @Delfino. I took a look at the link. It seems to be the same thing, but it is not. Soen’s question is more comprehensive. Mine is more specific. I want to recover the type (T) from a List<T>.
– Geison Santos
Yes, indeed, the code structure is so similar that at first glance it looks the same. I even tried to find a solution for you, but it really doesn’t seem possible, I tried several ways, and as far as I went there is no way.
– Delfino
Your code makes no sense. T is a class type Parameter Foo and clazz is declared to be of this type type Parameter. Then you try to set to this variable a list type type Parameter, but the variable is not of the type list... It is difficult to understand its objective. Anyway, the Java Generic does not offer resource for you to resgar the type type Parameter at runtime.
– Caffé
@Caffé, perhaps you are correct, however the purpose of the code was to convey my need. I need to somehow receive a list of type Parameter and assign value to my clazz attribute. For suspecting that this is not possible I gave the dirty to adapt the code of the question.
– Geison Santos
The problem with your code not making sense is that you can’t understand exactly what you need; the object of the code has not been reached, its need has not been conveyed. Anyway, as demonstrated in my reply and explained the reason, infer the type of T using Generics features is not possible. If you want the type, you need to enter it in another parameter. For example:
Foo(List<T> list, Class<T> type) { ... }
.– Caffé
@Caffé, the example you provided here in the commentary is precisely the type of change I suggested in case of impossibility of a solution using the code as it is. It would be interesting to complement this in his reply.
– Geison Santos