有些方法需要类文字作为参数。
Collection<EmpInfo> emps =
SomeSqlUtil.select(
EmpInfo.class,
"select * from emps");
或
GWT.create(Razmataz.class);
当我需要提供通用的特定类时,问题就出现了
EmpInfo<String>
Razmataz<Integer>
下面的语法是错误的
Collection<EmpInfo<String>> emps =
SomeSqlUtil.select(
EmpInfo<String>.class,
"select * from emps");
或
GWT.create(Razmataz<Integer>.class);
因为你不能做这样的语法
Razmataz<Integer>.class
那么,我怎样才能从中挤出一个类字面量
EmpInfo<String>
Razmataz<Integer>
这样我就可以将它们作为参数提供给需要类文字的方法?
更多信息
好吧,我承认我问这个主要是为了 GWT。
我有一对 GWT RPC 接口(interface) Razmataz。 (仅供引用,GWT RPC 接口(interface)必须在服务器-客户端对中定义)。我计划使用相同的接口(interface)对来进行通信,无论是字符串、整数、 boolean 值等。
GWT.create(Razmataz)
对于 Razmataz<T>
提示说,由于我没有指定 T,GWT 编译器将其视为对象。然后 GWT 编译器将不接受 Object 类。它需要比对象更具体。
所以,我似乎无法告诉 GWT.create T 是什么,因为类字面量是运行时概念,而泛型是编译时概念,对吗?
最佳答案
引自 Java Generics and Collections , 第 7.2 节:
Class literals are also restricted; it is not even syntactically valid to supply a type parameter to the type in a class literal. Thus, the following fragment is illegal:
class ClassLiteral {
public Class<?> k = List<Integer>.class; // syntax error
}
Indeed, Java's grammar makes a phrase such as the preceding one difficult to parse, and it may trigger a cascade of syntax errors [...]
This syntax problem leads to an irregularity. Everywhere else that a reifiable type is required, you may supply either a raw type (such as
List
) or a parameterized type with unbounded wildcards (such asList<?>
). However, for class tokens, you must supply a raw type; not even unbounded wildcards may appear. ReplacingList<Integer>
withList<?>
in the preceding code leads to a similar error cascade.
所以,你别无选择,只能在类标记中使用原始类型,比如
GWT.create(Razmataz.class);
关于java - 如何从一般特定的类中获取类文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2864154/