在 Java 中使用类名在运行时创建对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17105167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:00:14  来源:igfitidea点击:

Create array of objects at run time using class name in java

javaobject

提问by Waqas Ali

We all know we can create an object with the help of class name in the string format. Like i have a class name "Test". Using

我们都知道我们可以在字符串格式的类名的帮助下创建一个对象。就像我有一个类名“测试”。使用

Class.forName("Test").newInstance()

We can create the object of that class.

我们可以创建那个类的对象。

My question is that is there any way to create an array or array list of the objects using class name ?? OR lets suppose we have an object of the class and can with this object we create the array or array list of the that object.

我的问题是有没有办法使用类名创建对象的数组或数组列表?OR 让我们假设我们有一个类的对象,并且可以使用这个对象创建该对象的数组或数组列表。

回答by Jon Skeet

To create an array, you can use java.lang.reflect.Arrayand its newInstancemethod:

要创建数组,您可以使用java.lang.reflect.Array及其newInstance方法:

Object array = Array.newInstance(componentType, length);

Note that the return type is just Objectbecause there's no way of expressing that it returns an array of the right type, other than by making it a generic method... which typically you don't want it to be. (You certainly don't in your case.) Even then it wouldn't cope if you passed in int.class.

请注意,返回类型只是Object因为无法表示它返回正确类型的数组,除了将其设为泛型方法......通常您不希望它成为。(在你的情况下你当然不会。)即使这样,如果你传入int.class.

Sample code:

示例代码:

import java.lang.reflect.*;

public class Test {
    public static void main(String[] args) throws Exception {
        Object array = Array.newInstance(String.class, 10);

        // This would fail if it weren't really a string array
        String[] afterCasting = (String[]) array;
        System.out.println(afterCasting.length);
    }
}

For ArrayList, there's no such concept really - type erasure means that an ArrayListdoesn't really know its component type, so you can create anyArrayList. For example:

对于ArrayList,实际上没有这样的概念 - 类型擦除意味着 anArrayList并不真正知道其组件类型,因此您可以创建任何ArrayList. 例如:

Object objectList = new ArrayList<Object>();
Object stringList = new ArrayList<String>();

After creation, those two objects are indistinguishable in terms of their types.

创建后,这两个对象在类型方面无法区分。

回答by NINCOMPOOP

You can use Array

您可以使用数组

Object xyz = Array.newInstance(Class.forName(className), 10);

It has a method newInstance(Class, int):

它有一个方法newInstance(Class, int)

Creates a new array with the specified component type and length. Invoking this method is equivalent to creating an array as follows:

创建具有指定组件类型和长度的新数组。调用这个方法相当于创建一个数组如下:

 int[] x = {length};
 Array.newInstance(componentType, x);