In the K&B SCJP book I have read that generic types are only for the compilation type. After it, they are removed and they look like old non generic classes. Here I paste 2 codes for which I would like any of you to explain me (please!!!) how it happens that I can actually get the generic type during the run time.
In the first code, we extend the generic class and then through the subclass we are able to get the generic type of the superclass:
The output is:
The second code does the same but without extending:
And the output is:
Can anyone help me with understanding this 2 codes?
The methods that you're using are part of reflection. That is a mechanism which examines the code at runtime. So you can query the names of methods of a certain class for example. It also allows you to view the generic information. It is however generally considered a bad programming style (of course there are a lot of exceptions) because most problems can be solved with a good use of OOP and architecture. One of the problems of reflection is that you lose compile-time checks made by the compiler.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Joined: Jul 15, 2010
Thanks for the answer. So does it mean that if I use a reflection (I import some field from reflection package) then the compiler doesn't remove the information about the used parameters in the generic types?
Jan Osykowski wrote:So does it mean that if I use a reflection (I import some field from reflection package) then the compiler doesn't remove the information about the used parameters in the generic types?
No. reflection is a runtime mechanism . and type erasure happens at compile time. what wouter meant is getting a genetic type information at runtime is possible through reflection APIs, though it is not general practice. go through the earlier discussion in java ranch, below is the link
Here I have one doubt, probably I will ask in Java General forum
Joined: Jul 15, 2010
So as I read in the refered topic, the information about the parameterized generic type is not actually erased but it is still saved in the .class file and that's why a reflection can access it?
What doubt do you have about these examples? If you add a new topic in a different subforum please let me know.