I have the following Java code;
PagedResponse<Person> response = new PagedResponse<Person>();
TypedQuery<Person> query = getNamedQuery("Person.findSpecific", Person.class);
response = executePagedTypedQuery(query);
Now executePagedTypedQuery is defined as;
protected <T> PagedResponse<T> executePagedTypedQuery(TypedQuery query) {
PagedResponse<T> response = new PagedResponse<T>();
List<T> resultList = query.getResultList();
}
Now I want that inside executePagedTypedQuery() method, the type T should be set to "Person", which is what I am passing. But for some reason, on debugging, it says
T = >"T" is not a known variable in the current context.<
Am I passing the parameter incorrectly ?
If you change the signature to
protected <T> PagedResponse<T> executePagedTypedQuery(TypedQuery<T> query)
then when you pass in your query, T
will be chosen accordingly.
You're not invoking the method incorrectly; T
is not passed as a parameter to the method.
Generics in Java are basically compile-time syntactic sugar to prevent you having to do lots of casts everywhere. The compiler will generate the compiled code of the method assuming that all references to T
are references to the maximal parent type T
if it has a type constraint, or Object
if it doesn't have a constraint. This is called type erasure .
Contract this with the situation in C# - type parameters are actually accessible to your code, so you can write things like new T();
or typeof(T)
(equivalent to Java T.class
) in your method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.