[英]Java Determine type T at runtime
I have the following Java code; 我有以下Java代码;
PagedResponse<Person> response = new PagedResponse<Person>();
TypedQuery<Person> query = getNamedQuery("Person.findSpecific", Person.class);
response = executePagedTypedQuery(query);
Now executePagedTypedQuery is defined as; 现在executePagedTypedQuery定义为;
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. 现在,我希望在executePagedTypedQuery()方法内部,将类型T设置为“ Person”,这就是我要传递的内容。 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. 那么当您传递查询时,将相应地选择
T
You're not invoking the method incorrectly; 您不会错误地调用该方法;
T
is not passed as a parameter to the method. T
不作为参数传递给方法。
Generics in Java are basically compile-time syntactic sugar to prevent you having to do lots of casts everywhere. Java中的泛型基本上是编译时语法糖,以防止您不得不在任何地方进行大量强制转换。 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. 假设所有对
T
的引用都是对最大父类型T
引用(如果它具有类型约束),则假定该对象是对最大父类型T
引用;如果没有约束,则将生成Object
。 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();
与C#中的情况联系起来-类型参数实际上是您的代码可访问的,因此您可以编写诸如
new T();
类的东西new T();
or typeof(T)
(equivalent to Java T.class
) in your method. 或
typeof(T)
(相当于Java T.class
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.