1

I am trying to create an object creator that asks the user for input and then creates an object. I have an array of Contructors for a given class, with these contructors, I let the user choose one and if that constructor has parameters, I would like the user to set those parameters on the fly.

With the constructor list from java.lang.reflect.Constructor; given below:

constructorList[0].getGenericParameterTypes()[0]

This returns an array of 'Type'

Is it possible to create an instance of this type given some value by the user? Say its an int type, if I wanted that int to be 10 -- (I know this wont work but theoretically)

constructorList[0].getGenericParameterTypes()[0] intValue = 10;

If its an object, I can get the class from Type and ...I guess I can just make a recursive call to the objectcreator I am making, would there be an easy way to create a new instance of that object because I feel like this can go into a never ending recursion loop.

1 Answer 1

1

In general I don't see any fundamental problems with primitives. Though you should consider, that Type is a very abstract declaration, so it includes not only concrete classes, but also such things like parameter variables, parameterised types etc. I guess, it will be useful to remember, that primitives are very specific types (classes), and they are not explicitly constructed (since they're literally declared in code are handled 'by value' in memory); so I guess, their 'boxed' versions will be used instead.

Though you should consider, that type checks will not be applied, so you'll need manually ensure, that all inputs are valid, and properly cast method results.

Here is a sample code, which may inspire you:

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    String typeName = s.next();

    //ask for type

    Class<?> type;

    try {
        type = Class.forName(typeName);
    } catch (ClassNotFoundException e) {
        System.out.printf("Class `%s` was not found%n", typeName);
        return;
    }

    //discover constructors

    Constructor<?>[] constructors = type.getConstructors();

    for (int i = 0; i < constructors.length; ++i) {
        System.out.printf(" > %d %s%n", i, constructors[i]);
    }

    //select constructor and list its parameters

    int constructorIndex = s.nextInt();
    Constructor<?> constructor = constructors[constructorIndex];

    Type[] parameterTypes = constructor.getGenericParameterTypes();
    for (Type parameterType : parameterTypes) {
        System.out.println(parameterType);

        //each type implementation requires a specific processing

        if (parameterType instanceof Class) {
            Class parameterClass = (Class) parameterType;
            if ((parameterClass).isPrimitive()) {

                //simple int primitive; which can be directly obtained from scanner

                if (Integer.TYPE.isAssignableFrom(parameterClass)) {
                    System.out.println("\tinteger primitive > ");
                    int value = s.nextInt();
                    System.out.println("\t you've entered " + value);
                }
            } else {
                Stream.of((parameterClass).getConstructors()).forEach(c -> System.out.printf("\t%s%n", c));
                Stream.of((parameterClass).getDeclaredConstructors()).forEach(c -> System.out.printf("\t%s%n", c));
            }
        }
    }

    // here we consider a sample java.lang.Integer class was requested with #0 constructor

    if (Integer.class.isAssignableFrom(type) && constructorIndex == 0) {

        System.out.println("Input an integer number: ");

        String value = s.next();

        // since newInstance requires array of objects, we need to create an object (not primitive)

        Object instance;

        try {
            instance = constructor.newInstance(Integer.valueOf(value));
        } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            return;
        }

        System.out.printf("%s %s%n", instance.getClass(), instance);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.