0

How to make ConstructorUtils.invokeConstructor work even when a value is stored in a string?

here is the code:

    public static void main(String[] args) {
    try {
        String type     = "java.lang.Character";
        //char value     = 'c';  //this work
        String value = "c"; // this not work,throws[java.lang.NoSuchMethodException: No such accessible constructor on object: java.lang.Character]
        Class<?> clazz  = ClassUtils.getClass(type);
        Object instance = ConstructorUtils.invokeConstructor(clazz, value);
        System.out.println(instance);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
kinjia
  • 41
  • 5

1 Answers1

0

ConstructorUtils.invokeConstructor(clazz, value); this expression tries to invoke a construction on the clazz class with the argument value.

java.lang.Character only has the following constructor that accepts a character as the argument,

public Character(char value) {
    this.value = value;
}

It does not have a construction that can accept a String argument, so when you invoke ConstructorUtils.invokeConstructor(clazz, value);, it throws java.lang.NoSuchMethodException and says No such accessible constructor on object: java.lang.Character.

To create a String class instance, you have to apply it on java.lang.String. Change String type = "java.lang.Character"; to String type = "java.lang.String";

Sazzadur Rahaman
  • 6,938
  • 1
  • 30
  • 52
  • I found answer in https://stackoverflow.com/questions/13868986/dynamically-create-an-object-in-java-from-a-class-name-and-set-class-fields-by-u ,and must convert type manually very thanks! – kinjia Jul 14 '18 at 04:24