创建一个对应于泛型类型的Type对象 [英] Creating a Type object corresponding to a generic type

查看:90
本文介绍了创建一个对应于泛型类型的Type对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如何为 Map< String,String> ? Type >

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆