创建一个对应于泛型类型的Type对象 [英] Creating a Type object corresponding to a generic type
问题描述
在Java中,如何为 Map< String,String>
?
System.out.println(Map< String,String> .class);
不能编译。我能想到的一种解决方法是:
Map< String,String> dummy(){throw new Error(); }
类型mapStringString = Class.forName(ThisClass)。getMethod(dummy,null).getGenericReturnType();
这是正确的方法吗?
public class Test {
public Map< String,String>假;
public static void main(String ... args)throws SecurityException,
NoSuchFieldException {
类型mapStringString = Test.class.getField(dummy)。getGenericType();
// ...
轻微 hack ..
正如Tom Hawtin所建议的那样,您可以自己实现这些方法:
类型mapStrStr2 = new ParameterizedType(){
public Type getRawType(){
return Map.class;
}
public Type getOwnerType(){
return null;
}
public Type [] getActualTypeArguments(){
return new Type [] {String.class,String.class};
}
};
返回与 ParameterizedType
。第一种方法的结果甚至是 .equals
这种类型。 (但是,这种方法不会覆盖toString,equals等等,所以根据您的需要,第一种方法可能仍然会更好。)
In Java, how can I construct a Type
object for Map<String, String>
?
System.out.println(Map<String, String>.class);
doesn't compile. One workaround I can think of is
Map<String, String> dummy() { throw new Error(); }
Type mapStringString = Class.forName("ThisClass").getMethod("dummy", null).getGenericReturnType();
Is this the correct way?
public class Test {
public Map<String, String> dummy;
public static void main(String... args) throws SecurityException,
NoSuchFieldException {
Type mapStringString = Test.class.getField("dummy").getGenericType();
// ...
Is a slightly less ugly hack..
As Tom Hawtin suggests, you could implement the methods yourself:
Type mapStrStr2 = new ParameterizedType() {
public Type getRawType() {
return Map.class;
}
public Type getOwnerType() {
return null;
}
public Type[] getActualTypeArguments() {
return new Type[] { String.class, String.class };
}
};
returns the same values as the other approach for the methods declared in ParameterizedType
. The result of the first approach even .equals
this type. (However, this approach does not override toString, equals and so on, so depending on your needs, the first approach might still be better.)
这篇关于创建一个对应于泛型类型的Type对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!