azhar baloch azhar baloch - 3 years ago 203
Java Question

NoSuchMethodException while getting the constructor through reflection in java

Below is the code in which I am trying to get the constructor of java class ArrayList which accepts one Integar value. But I am getting NoSuchMethodException.

Actual error is: java.lang.NoSuchMethodException: java.util.ArrayList.(java.lang.Integer)

import java.util.*;
import java.lang.reflect.Constructor;
public class MyClass {
public static void main(String args[]) {
try
{
Class obj = Class.forName("java.util.ArrayList");
Class [] arglist = new Class[1];
arglist[0] = Integer.class;

Constructor con = obj.getConstructor(arglist);
System.out.println("Constructor found:" +con.toString());
}
catch(ClassNotFoundException a)
{
System.out.println(a);

}
catch (NoSuchMethodException b)
{
System.out.println(b);
}
}
}

Answer Source

The ArrayList class indeed doesn't have a constructor that takes a java.lang.Integer. It does, however, have a constructor that takes a primitive int. These two are not interchangeable, and you'll have to use the correct Class object:

arglist[0] = int.class;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download