简体   繁体   中英

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 :)

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;
}

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