L
learningjava
Hello,
I am trying to use reflection to create a new instance of an inner
class
(and hence use it later).
The code compiles fine, but throws a NoSuchMethodException on runtime.
Can you please comment on and provide the right approach to
do this?
Thanks,
StrugglingWithReflection
code:
****
import java.lang.reflect.*;
public class Reflection {
private class InnerClass1 {
//default constructor
public InnerClass1() { }
public String description() {
return "InnerClass 1";
}
}
public static void main(String[] args) throws ClassNotFoundException,
NoSuchMethodException,
InstantiationException, IllegalAccessException,
InvocationTargetException
{
//trying to create a new instance of the inner class
//code compiled with no syntax errors
Class cls = Class.forName("Reflection$" + "InnerClass1");
Class[] partypes;
partypes = new Class[1];
partypes[0] = Long.TYPE;
//this throws a NoSuchMethodException (runtime error). why?
//the exception text also has something like <init>
//what does it mean?
Constructor con = cls.getConstructor(partypes);
Object[] arglist;
arglist = new Object[1];
arglist[0] = new Long(500);
Object methobj = con.newInstance(arglist);
}
}
****
I am trying to use reflection to create a new instance of an inner
class
(and hence use it later).
The code compiles fine, but throws a NoSuchMethodException on runtime.
Can you please comment on and provide the right approach to
do this?
Thanks,
StrugglingWithReflection
code:
****
import java.lang.reflect.*;
public class Reflection {
private class InnerClass1 {
//default constructor
public InnerClass1() { }
public String description() {
return "InnerClass 1";
}
}
public static void main(String[] args) throws ClassNotFoundException,
NoSuchMethodException,
InstantiationException, IllegalAccessException,
InvocationTargetException
{
//trying to create a new instance of the inner class
//code compiled with no syntax errors
Class cls = Class.forName("Reflection$" + "InnerClass1");
Class[] partypes;
partypes = new Class[1];
partypes[0] = Long.TYPE;
//this throws a NoSuchMethodException (runtime error). why?
//the exception text also has something like <init>
//what does it mean?
Constructor con = cls.getConstructor(partypes);
Object[] arglist;
arglist = new Object[1];
arglist[0] = new Long(500);
Object methobj = con.newInstance(arglist);
}
}
****