Creating a Type object corresponding to a generic type

ぃ、小莉子 提交于 2019-12-05 00:19:13

问题


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?


回答1:


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.)




回答2:


It's all done with interfaces, so you can construct your own implementation.

However, the easiest way is to use reflection on a dummy class created for the purpose.




回答3:


Yes it is the correct and the only way to get the generics at runtime. The type is erased ("type erasure"), the Bytecode-Map is actualy an Object-to-Object Map, the generics defintion in the source code are only used by the compiler to assure type safety.



来源:https://stackoverflow.com/questions/2989055/creating-a-type-object-corresponding-to-a-generic-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!