0

While creating instance of subclass Y

public class X implements I{
    ...

    ...
    public class Y implements I{
        ...

        ...
    }
}

by

o = c.newInstance();

where c is Y class I am getting this exception:

java.lang.InstantiationException: com.gmail.kubuxu.ms2d.Commands.VersionCommand$CCommand
    at java.lang.Class.newInstance0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at com.gmail.kubuxu.ms2d.CommandProcessor.<init>(CommandProcessor.java:22)
    at com.gmail.kubuxu.ms2d.Conns.CommandServerProtocol.<init>(CommandServerProtocol.java:13)
    at com.gmail.kubuxu.ms2d.Conns.ClientConn.run(ClientConn.java:40)
    at java.lang.Thread.run(Unknown Source)

Can someone say what I am doing wrong.

Kubuxu
  • 295
  • 2
  • 12
  • 2
    This can't work anyway since the inner class is not static. Instantiation of it requires an outer instance. – AllTooSir May 16 '13 at 16:25

2 Answers2

0

Since Y is non-static inner class of X, you cannot create instance of Y directly

like

Class clazz = Y.class
Y ref = clazz.newInstance();

You need to do as explained in this thread

Class<X> oc = X.class;
Class<?> c = Class.forName("X$Y");
Constructor<?> con = c.getConstructors()[0];
Y i = (Y)con.newInstance(oc.newInstance());
System.out.println(i);
Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
0

The class Y is a non-static nested class. You can't create it without an instance of the class X.

Depending on your needs, the easiest solution for you might be to make it static:

public static class Y implements I{
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151