mardi 18 juillet 2017

Java Reflection - get type of arguments received as input from a file

I have a text file that I pass as an argument to my program. The file contains class names and arguments that I should instantiate:

Home:
SmartMeter:30,false

I want to create the instances, using reflection but I can't figure out how to get the actual type of the arguments I am getting from the file. After I get this I want to compare them to the parameter types of all the constructors for this class and pick the right one. Here is the code I have written so far:

    Scanner scan = new Scanner(new File(args[0]));
    String[] classNameAndParameters;
    String[] parameters;

    while (scan.hasNextLine()) {
        classNameAndParameters = scan.nextLine().split(":");
        Class<?> c = Class.forName(classNameAndParameters[0]);

        // i check for the length too because it throws arrayoutofbounds exception
        if (classNameAndParameters.length > 1 && classNameAndParameters[1] != null) {
            parameters = classNameAndParameters[1].split(",");


            // get all constructors for the created class
            Constructor<?>[] constructors = c.getDeclaredConstructors(); 

            for(int i = 0; i < constructors.length; i++) {
                Constructor<?> ct = constructors[i];
                Class<?> pvec[] = ct.getParameterTypes();

                for (int j = 0; j < pvec.length; j++) {
                    System.out.println("param #" + j + " " + pvec[j]);
                }
            }
            //i should match the parameter types of the file with the parameters of the available constructors


            //Object object = consa.newInstance();
        } else {
            // default case when the constructor takes no arguments
            Constructor<?> consa = c.getConstructor(); 
            Object object = consa.newInstance();
        }
    }

    scan.close();





Aucun commentaire:

Enregistrer un commentaire