简体   繁体   English

获取泛型类型的数组类

[英]Get array class of generic type

I have a class with a generic type. 我有一个泛型类。 import java.lang.reflect.Array; import java.lang.reflect.Array;

public abstract class MyClass<T> {

    private Class<T> clazz;
    private Class<?> arrayClazz;

    public MyClass() {
        clazz = ClassUtils.getParameterizedClass(getClass());
        arrayClazz = Array.newInstance(clazz, 0).getClass();
    }
}

The Utils method reads the generic type of the given class so I don't have to pass the same class as a constructor parameter. Utils方法读取给定类的泛型类型,因此我不必将同一个类作为构造函数参数传递。 What I'm trying to achieve is getting the array class of clazz. 我想要实现的是获得数组类的clazz。

For example if T is String then 例如,如果T是String,那么

clazz = String.class;
arrayClazz = String[].class;

I currently solved it by creating a new instance of T[] and reading its class. 我目前通过创建一个新的T []实例并读取它的类来解决它。 I wanted to know if there's a better way or if there are any downsides with this method. 我想知道是否有更好的方法,或者这种方法是否有任何缺点。

Update 更新

What I'm trying to do: I have a generic DataProvider which requests JSON from a server. 我正在尝试做什么:我有一个从服务器请求JSON的通用DataProvider。 I use GSON to parse the response. 我使用GSON来解析响应。

public abstract class DataProvider<T> {

    private final Class<T> resourceClass;
    private final Class arrayClass;


    protected DataProvider() {
        this.resourceRootPath = resourceRootPath;
        this.resourceClass = ClassUtils.getParameterizedClass(getClass());
        arrayClass = Array.newInstance(resourceClass, 0).getClass();
    }

    public void get(String id) {
        ...
        T obj = gson.fromJson(response.body().charStream(), resourceClass)
        ...
    }

    public void list(String id) {
        ...
        T[] objs = gson.fromJson(response.body().charStream(), arrayClass)
        ...
    }
}

You should look up Type Erasure , which may prevent a clean way of doing what you're asking for. 你应该查找Type Erasure ,它可能会阻止你做出你想要的干净方式。 (Generics can't help you here.) (仿制药在这里帮不了你。)

The problem is that in Java, generic type data is used at compile time to ensure everything looks good... and then Java forgets about it entirely. 问题是在Java中,在编译时使用泛型类型数据以确保一切看起来都很好......然后Java完全忘记它。 The types aren't compiled in in the way you'd hope, they're just gone. 这些类型没有以您希望的方式编译,它们刚刚消失。

Because of that, your approach is (I think!) the cleanest, even if it feels hacky. 正因为如此,你的方法(我认为!)是最干净的,即使它感觉很酷。 You need to instantiate one and use reflection to get it's type. 您需要实例化一个并使用反射来获取它的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM