简体   繁体   中英

Java Class.newInstance error

In the following code, I am getting java.lang.InstantiationException

(Below is trimmed down code that compiles standalone - in my application I want to maintain an Enum->Class map, and on reading integer values from a file, instantiate appropriate class looking into the map).

How to get rid of the error? Is there a syntax problem? Must I use Interfaces? My understanding here is limited.

class Main {
    abstract class Base {
        Base() {};
        void print() {
            System.out.println("I am in Base");
        }
    }


    class D1 extends Base {
        D1() {};
        @Override 
        void print() {
            System.out.println("I am in D1");
        }
    }

    static Class<? extends Base> getMyClass() {
        return D1.class;
    }


    public static void main(String[] args) {
        try {
            Class<?> cc = getMyClass();
            Object oo = cc.newInstance();
            Base bb = (Base) oo; 
            bb.print();

        } catch (Exception ee) {
            System.out.println(ee);
        };
    }
};

Your code has two problems:

  • Base and D1 are non-static inner classes. It means that they can access fields and methods of their declaring class ( Main ), therefore they should hold a reference to the instance of Main . Therefore their constructors have an implicit argument of type Main which is used to pass that reference. So, they don't have no-args constructors and you should use a single-argument constructor instead:

     Object oo = cc.getConstructor(Main.class).newInstance(new Main()); 

    Alternatively, you can simply declare them as static , or declare them outside of Main - in this case they won't be able to access member of Main and won't require a reference to it.

  • Constructor of D1 should be public . Otherwise you need to call setAccessible(true) to make it accessible for reflection.

As both the classes Base and D1 are inner classes with same time they are non-static inner classes so their methods can be accessed by creating objects inner classes inside Main class and you can call their methods inside Main constructor and it will look something like this ..

class Main {   
      Main(){     
      D1 dd = new D1();  
      }  
      abstract class Base {  
          Base() {};  
          void print() {  
                System.out.println("I am in Base");  
          }  
      }
     class D1 extends Base {
          D1() {};
          @Override 
          void print() {
              System.out.println("I am in D1");
          }
     }

}

Hope this will help you .. thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM