samedi 21 mars 2020

How to use varargs as parameters of newInstance() to call a constructor and create an instance?

I'm an autodidact and I'm trying to do this homework, but I didn't find any solution yet.

I don't know how to use varargs.I can't pass them to the newInstance() method to invoke the constructor that I need. But the main problem is that I would like to write them from the command line using "args" but I don't know how to do.

Please any advice? Thanks a lot!

import java.lang.reflect.*;
import java.io.*;

public class Test0 {

    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]);
        }
        catch(ClassNotFoundException e){
            e.printStackTrace();
            System.exit(1);
        }
        System.out.println(theClass);

        Object obj = null;
        if(theClass.isInterface()) {
        System.out.println("the class is an interface!");
        System.exit(1);
        }
        System.out.print("number of constructor's parameters :");
        System.out.println();
        String buf = null;
        try{
            buf = br.readLine();
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
        String[] params = {"first", "second"," more"};
        Constructor[] constructors = theClass.getConstructors();
        for(Constructor constructor : constructors) {
            if(constructor.getParameterCount() == Integer.parseInt(buf)) { 
                if(constructor.getParameterTypes()[0] == String.class){
                    try{
                        obj = constructor.newInstance((Object) params);//HERE IS THE PROBLEM
                    }
                    catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                        System.exit(1);
                    }
                }
            }
        }
        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'");
        }
    }

}




Aucun commentaire:

Enregistrer un commentaire