后续:从类名创建一个对象数组 [英] Follow Up: Create an an array of objects from classname

查看:137
本文介绍了后续:从类名创建一个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在追踪此问题, 1268817

在问题中,我们找到一种方法来创建一个对象的isntance给定一个类的名称(作为字符串)。

In the question, we find a way to create an isntance of an object given a the name (as a string) of the class.

但是如何创建一个数组

我在想的东西,但似乎没有工作

I was thinking something in the line of but doesnt seem to work

Object[] xyz = Class.forName(className).newInstance()[];


推荐答案

Object objects = java.lang.reflect.Array.newInstance(Class.forName(classname), 10);

包含10个元素的数组。

For an array of 10 elements.

令人讨厌的是,它返回一个对象,而不是一个对象数组。

Annoyingly it returns an object, instead of an object array.

正如Tom指出的,这是允许:

As Tom points out, this is to allow:

Object objects = java.lang.reflect.Array.newInstance(int.class, 10);

一个int []不能赋给一个Object [],所以返回类型必须是目的。但它仍然恼人,因为你很少想这样做。

An int[] is not assignable to an Object[], so the return type has to be an Object. But it is still annoying as you very rarely want to do this.

这篇关于后续:从类名创建一个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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