How to instantiate an object with multiple parameters by the Java reflection mechanism?

Class [] argsClass = new Class [2];

    argsClass[0] = Integer.class;
    argsClass[1] = String.class;
    User user2 = (User) userClass.getConstructor(argsClass).newInstance(new Object[]{12, "awe"});

error message:
java.lang.NoSuchMethodException: com.bean.User. < init > (java.lang.Integer, java.lang.String)

at java.base/java.lang.Class.getConstructor0(Class.java:3322)
at java.base/java.lang.Class.getConstructor(Class.java:2108)
Mar.04,2021

I guess your first parameter should be int type, not Integer , so modify this code:

argsClass[0] = Integer.class;

modify to:

argsClass[0] = int.class;

put

argsClass[0] = Integer.class;
Change

to

argsClass[0] = Integer.TYPE;

if the attribute type in your user class is Integer, you should use Integer.TYPE if Integer.class, is int.

Menu