Java中的泛型 - 实例化T [英] generics in Java - instantiating T

查看:95
本文介绍了Java中的泛型 - 实例化T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有以下代码:

I have the following code in Java:

public static<T> void doIt(Class<T> t)
{
    T[] arr;
    arr = (T[])Array.newInstance(t, 4);
}

我希望能够使用doIt这样的基本类型,例如double和使用类对象如String。

I want to be able to use doIt using both primitive type such as double and using class objects such as String.

我可以通过使用(代码编译)来完成它:

I could do it by using (code compiles):

    doIt(double.class);
    doIt(String.class);

然而,我担心在第一种情况下,Java编译器实际上会包装双原始类型使用Double类,我不想要。我实际上希望它在这种情况下实例化一个基本数组(同时用String情况实例化一个对象数组)。有人知道doIt(double.class)会发生什么吗?它是实例化为Double还是Double?

However, I am worried that in the first case, the Java compiler will actually wrap the double primitive type using a Double class, which I don't want. I actually want it to instantiate a primitive array in this case (while instantiating an objects array with the String case). Does someone know what happens with doIt(double.class)? Is it instantiated as Double or double?

谢谢。

推荐答案

您实际上无法在这里实现 T = double - Java泛型不适用于原始类型。但是,您仍然可以实例化您的数组:

You couldn't actually make T = double here - Java generics simply don't work with primitive types. However, you can still instantiate your array:

import java.lang.reflect.*;

public class Test {
    public static void main(String[] args) {
        createArray(double.class);
    }

    private static void createArray(Class<?> clazz) {
        Object array = Array.newInstance(clazz, 4);
        System.out.println(array.getClass() == double[].class); // true
    }
}

这取决于你想要的事后处理数组。

It really depends on what you want to do with the array afterwards.

这篇关于Java中的泛型 - 实例化T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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