将类类型作为参数传递给ArrayList使用? [英] Pass class type as parameter to use in ArrayList?

查看:438
本文介绍了将类类型作为参数传递给ArrayList使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个java方法,它接受一个类(不是一个对象),然后用该类创建一个ArrayList作为数组中每个成员的元素。伪代码示例:

I need to write a java method which takes a class (not an object) and then creates an ArrayList with that class as the element of each member in the array. Pseudo-code example:

public void insertData(String className, String fileName) {
      ArrayList<className> newList = new ArrayList<className>();
}

如何用Java实现这一目标?

How can I accomplish this in Java?

推荐答案

您可以使用通用方法

public <T> void insertData(Class<T> clazz, String fileName) {
   List<T> newList = new ArrayList<>();
}

但是如果你应该使用这个合约 insertData(String className,String fileName),你不能使用泛型,因为Java的编译时无法解析列表项的类型。

but if you should use this contract insertData(String className, String fileName), you cannot use generics because type of list item cannot be resolved in compile-time by Java.

在这种情况下,您根本不能使用泛型,并在将其放入列表之前使用反射来检查类型:

In this case you can don't use generics at all and use reflection to check type before you put it into list:

public void insertData(String className, String fileName) {
    List newList = new ArrayList();

    Class clazz;
    try {
        clazz = Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e); // provide proper handling of ClassNotFoundException 
    }

    Object a1 = getSomeObjectFromSomewhere();

    if (clazz.isInstance(a1)) {
        newList.add(a1);
    }
    // some additional code
}

但没有您只能使用 Object 的类的信息,因为您无法在代码中将对象转换为UnknownClass。

but without information of class you're able use just Object because you cannot cast your object to UnknownClass in your code.

这篇关于将类类型作为参数传递给ArrayList使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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