简体   繁体   English

Object []数组中泛型类的调用方法

[英]Call Method of Generic Class within an Object[] Array

I have a generic class, called Node<E> and I'm trying to define a static method that will return an array of objects of this type. 我有一个称为Node<E>的通用类,并且我试图定义一个静态方法,该方法将返回此类型的对象数组。 I understand that Java does not allow the creation of generic type arrays within a class so we have to create an Object array and pass our generic types through the object. 我知道Java不允许在类内创建泛型类型数组,因此我们必须创建一个Object数组,并将泛型类型通过该对象传递。

For an example of the code, let's define it as: 对于代码示例,我们将其定义为:

public static Object[] returnArray() {
    Object[] output;
    //code which adds Node<E> to output
    return output;

When I implement this code though, I am not able to: 但是,当我实现此代码时,我无法:

  • perform this class's methods on the objects within the array as they are of type Object 在数组中的对象上执行此类的方法,因为它们属于Object类型
    • If Node<E> had a method .getVal() the following code results in an error: 如果Node<E>具有.getVal()方法,则以下代码将导致错误:
      • Object[] nodes = Node.returnArray(head); nodes[0].getVal();
  • cast and return method array to a Node<E>[] array, even when explicit of the type. 将方法数组强制转换并返回到Node<E>[]数组,即使该类型是显式的也是如此。
    • Node<Integer>[] nodes = (Node<Integer>[]) Node.returnArray(head);

So the only way I am currently accessing the methods of each node is by assigning them to a variable by casting: 因此,我当前访问每个节点方法的唯一方法是通过强制转换将它们分配给变量:

Object[] nodes = Node.returnArray(head);
Node<Integer> returned1 = (Node<Integer>) nodes[0];
Node<Integer> returned2 = (Node<Integer>) nodes[1];

But you can see how redundant it gets as the code grows. 但是您可以看到,随着代码的增长,它变得多么冗余。 Is there a better way to access generic objects passed to an array? 有没有更好的方法来访问传递给数组的通用对象?

You can create generic arrays. 可以创建通用数组。 You just need the Class object for that. 您只需要Class对象即可。 Consider this overly complicated program for printing the number 6: 考虑以下过于复杂的程序来打印数字6:

public class GenericClass<T> {

    T[] array;

    public GenericClass(int length, Class<T> clazz) {
        array = (T[]) java.lang.reflect.Array.newInstance(clazz, length);
    }

    public T get(int i) {
        return array[i];
    }

    public T set(int i, T val) {
        return array[i] = val;
    }

    public static void main(String... args) {
        GenericClass<Integer> example = new GenericClass<>(5, Integer.class);
        example.set(0, 6);
        System.out.println(example.get(0)); //Prints 6
    }
}

This way, the array you create is really of type T[] , not Object[] , so it's safe to use and even externalize. 这样,您创建的数组实际上T[]类型,而不是Object[] ,因此可以安全使用,甚至可以进行外部化。 Another option, of course, is just to use a list. 当然,另一种选择是仅使用列表。

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

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