Search code examples
javaexceptioninner-classesinstantiationexception

java.lang.InstantiationException although a NoArgsConstructor is present


when I want to create an instance of my object TransLog, an InstantiationException is thrown even though I created a No-Args constructor in the class TransLog:

Caused by: java.lang.NoSuchMethodException: TransactionLogger$TransLog.<init>()
        at java.lang.Class.getConstructor0(Class.java:3082)
        at java.lang.Class.newInstance(Class.java:412)
        ... 20 more
@AllArgsConstructor
private class TransLog {
  public TransLog() {
  } 

  private int x; 
  private int y;
}

I create the instance in this way:

TransLog log = (TransLog) clazz.newInstance(); // clazz is TransLog.class

Thanks for your help in advance :)


Solution

  • You declared your TransLog class as a non-static inner class within the TransactionLogger class.

    That means the TransLog class has an implicit member variable referencing the enclosing TransactionLogger instance, and the constructors have an implicit additional argument of that type.

    It seems you don't want that. Therefore you need to declare the inner class as static:

    @AllArgsConstructor
    private static class TransLog {
        public TransLog() {
        }
    
        private int x;
        private int y;
    }