java class实例化对象_使用Class对象实例化Java类型参数/ generic

参见英文答案 > How to set the generic type of an ArrayList at runtime in java?????????????????????????????????????4个

如何实例化Java泛型对象,该对象仅接受类或参数给出的类型参数宾语?

例如:

通常,可以使用以下语法实例化Integer对象的ArrayList:

ArrayList foo = new ArrayList();

但是,给定一个Class诸如Integer.class之类的对象,怎么能创建一个类似的ArrayList?例如,我将如何做这样的事情(语法不正确):

ArrayList foo = new ArrayList();

我需要这个用于Java的非常不寻常的事情(创建一个开源工具,用于可视化用户提供的数据结构实例/他们编写的泛型类).以下是我将如何使用此代码的示例,该代码说明了我将获得的信息:

import java.util.ArrayList;

import java.util.List;

public class ArrayListFromClass {

// obviously this code does not work

public static void main(String[] args) {

Object givenObject = new Integer(4);

// I would not know it is Integer.class, a Class> object would be supplied by the user/ as a generic

Class> cls = givenObject.getClass();

List bar = new ArrayList();

// Where args[0] is "Integer.class"

List foo = new ArrayList();

// then I would be able to add to foo or bar with one or both of these techniques:

// printing givenObject.getClass() gives you java.lang.Integer, don't worry about the casting not working.

bar.add(cls.cast(givenObject));

Integer y = 6;

bar.add(y);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值