简体   繁体   English

Java中的泛型-实例化T

[英]generics in Java - instantiating T

I have the following code in Java: 我在Java中有以下代码:

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

I want to be able to use doIt using both primitive type such as double and using class objects such as String. 我希望能够同时使用原始类型(例如double)和类对象(例如String)来使用doIt。

I could do it by using (code compiles): 我可以使用(代码编译)来做到这一点:

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

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. 但是,我担心在第一种情况下,Java编译器实际上会使用Double类来包装double原语类型,这是我所不希望的。 I actually want it to instantiate a primitive array in this case (while instantiating an objects array with the String case). 我实际上希望它在这种情况下实例化一个原始数组(在用String实例化一个对象数组的同时)。 Does someone know what happens with doIt(double.class)? 有人知道doIt(double.class)会发生什么吗? Is it instantiated as Double or double? 实例化为Double还是double?

Thanks. 谢谢。

You couldn't actually make T = double here - Java generics simply don't work with primitive types. 您实际上不能在这里使T = double -Java泛型根本无法与原始类型一起使用。 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. 这实际上取决于您随后要对数组执行的操作。

You can make an array of primitive double like this: 您可以像这样使原始double数组:

double[] arr = (double[]) Array.newInstance(double.class, 0);

But you can't make this work with generics, because generic parameters are always reference types, not primitive types. 但是您不能使用泛型来实现,因为泛型参数始终是引用类型,而不是原始类型。

泛型将与对象一起使用,因此装箱后应为Double。

You can create a method that takes an array type instead of the element type and get around the problem that type parameters must be reference types since all array types are reference types. 您可以创建一个采用数组类型而不是元素类型的方法,并解决类型参数必须为引用类型的问题,因为所有数组类型均为引用类型。

<T> T doIt(Class<T> arrayType) {
  assert arrayType.getElementType() != null;
  return <T> Array.newInstance(arrayType.getElementType(), 4);
}

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

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