如何使用varargs作为newInstance()的参数来调用构造函数并创建实例



我是一个自学成才的人,我正在努力做这项功课,但我还没有找到任何解决方案。

我不知道如何使用varargs。我无法将它们传递给newInstance((方法来调用我需要的构造函数。但主要的问题是,我想从命令行使用"args"来编写它们,但我不知道该怎么做

有什么建议吗?非常感谢!

import java.lang.reflect.*;
import java.io.*;
public class VarargsTest{
public static void main(String[] args)throws IOException{
Class theClass = null;
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(System.in));
try{
theClass = Class.forName(args[0]); // what class I want to use ?
}
catch(ClassNotFoundException e){
e.printStackTrace();
System.exit(1);
}
System.out.println(theClass);
Object obj = null;
System.out.print("number of constructor's parameters :"); 
String buf = null;
try{
buf = br.readLine(); //Waiting the number of parameters for the constructor
}
catch(IOException ioe){
ioe.printStackTrace();
}
Constructor[] constructors = theClass.getConstructors(); // constructor of that class
for(Constructor constructor : constructors) {
if(constructor.getParameterCount() == Integer.parseInt(buf)) {//checking that the number of parameters are matching
if(constructor.getParameterTypes()[0] == VarargsC.class){// IL PRIMO PARAMETRO DEL COSTRUTTORE DEVE ESSERE DEL TIPO DELLA CLASSE
try{
obj = constructor.newInstance(new Object[]{"first", "second"," more"}); // trying some elements, but I would like use args[1]
}
catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
System.exit(1);
}
}
}
}
System.out.println();
System.out.println("There isn't a constructor with " + buf + " parameters");
System.out.println();
if(obj != null) {
System.out.println("I have instantiate an object!");
System.out.println(obj);
}else{
System.out.println("I'm not able to instantiate an object'");
}
}
}
class VarargsC{
String str1;
String str2;
String str3;
public VarargsC(String str1, String str2, String str3){
this.str1 = str1;   
this.str2 = str2;
this.str3 = str3;
}
public String toString(){
return "VarargsC{" +
"str1=" + str1 +"n" +
"str2=" + str2 +"n" +
"str3=" + str3 + "n" + ''' +
'}';
}
}

/*class VarargsC{
String[] data;
public VarargsC(String... str){
data = new String[5];
for(int i= 0; i< str.length; i++)
for(String a: str)
this.data[i] = a;
}
public void toString(String... str){
for(String a: str)
System.out.println(a + "n");
}
}*/

Java编程语言的varargs功能允许调用一个方法,该方法支持可变数量的参数,就像源代码中带有n参数的普通方法一样。在命令行上允许任意数量的参数与您的意图无关。

事实上,您的操作甚至不需要此源代码功能。您将接收数组中的命令行参数,该数组的长度反映了它们的编号。可以使用args.length检查阵列长度。

public class Test {
public static void main(String[] args) {
if(args.length == 0) {
System.err.println("specify <className> args...");
System.exit(1);
}
String className = args[0];
// remove the first element
args = Arrays.copyOfRange(args, 1, args.length);
Class<?> theClass;// don't initialize with null
try {
theClass = Class.forName(className);
}
catch(ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
throw new AssertionError(); // unreachable point
}
// constructor accepting n strings
Class<?>[] argTypes = new Class[args.length];
Arrays.fill(argTypes, String.class);
try {
Constructor<?> c = theClass.getConstructor(argTypes);
Object o = c.newInstance((Object[])args);
System.out.println("created " + o);
} catch(ReflectiveOperationException e) {
e.printStackTrace();
System.exit(1);
}
}
}

newInstance的调用没有使用varargs功能,因为在源代码级别,我们已经有了一个现有的数组。事实上,(Object[])强制转换的存在是为了明确表示我们不想使用varargs功能,即我们不想调用一个只接受单个数组参数的构造函数,而是一个接受数组所含字符串参数的构造函数。

请注意,您的示例代码的newInstance(new Object[]{"first", "second"," more"})也没有使用varargs,因为它显式地构造了一个数组,以与此答案的解决方案相同的方式调用newInstance(Object[])。varargs调用应该是newInstance("first", "second"," more"),只有当我们在编译时知道构造函数需要三个字符串参数时,它才有效。

最新更新