使⽤反射机制创建List<String>实例,它的类由第⼀个命令⾏参数指定,其他参数插⼊到列表中。 测试并运⾏程序。
时间: 2024-02-09 19:13:38 浏览: 91
好的,我可以帮你解答这个问题。以下是示例代码:
```java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
// 获取类名
String className = args[0];
// 获取 Class 对象
Class<?> clazz = Class.forName(className);
// 获取构造方法
Constructor<?> constructor = clazz.getConstructor();
// 创建 List<String> 实例
List<String> list = (List<String>) constructor.newInstance();
// 将其他参数插入到列表中
for (int i = 1; i < args.length; i++) {
list.add(args[i]);
}
// 输出列表
System.out.println(list);
}
}
```
在命令行中运行命令:
```
java Main java.util.ArrayList a b c
```
输出结果为:
```
[a, b, c]
```
这里使用了反射机制来获取类名和构造方法,并通过构造方法创建 List 实例。注意要强制转换类型为 `List<String>`。然后将其他参数插入到列表中,并输出列表。
阅读全文
相关推荐









