This is great to declare a method with the signature public <T> T getDate() .
However, it is not possible to implement a method that returns what you want. That the method at run time cannot depend only on its type parameter, because it does not know its type parameter.
To get an intuition for this, understand that any code written using generics can also be written equivalently without using generics, simply by deleting the general parameters and inserting the ghosts if necessary. This is what type erasure means.
Therefore, to find out if your method is possible in Generics, just ask how you would do it without Generics:
public Object getDate() {
If you cannot do this without Generics, you also cannot do this with Generics.
C ++ templates are completely different. For C ++ template functions and classes, templates generate a “separate copy” of a function or class for each type argument that is used with it. that is, the compiler accepts the boilerplate code and “copies and pastes” it into several versions, each separately. Therefore, each copy of the code is specific to a particular type argument and therefore can use this type at run time.
That's why C ++ - boilerplate code must be available in source form so that you can use it - there are no such templates as "compiled" ones. However, in Java, you can use a compiled generic class. Generic classes and methods in Java do not imply anything about the types that they can use.
newacct
source share