简体   繁体   English

java.lang.InstantiationException 虽然存在 NoArgsConstructor

[英]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 :当我想创建对象TransLogInstantiationException ,即使我在类TransLog创建了一个 No-Args 构造函数,也会抛出InstantiationException

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.您在TransactionLogger类中将TransLog类声明为非静态内部类。

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.这意味着TransLog类具有引用封闭TransactionLogger实例的隐式成员变量,并且构造函数具有该类型的隐式附加参数。

It seems you don't want that.看来你不想那样。 Therefore you need to declare the inner class as static :因此,您需要将内部类声明为static

@AllArgsConstructor
private static class TransLog {
    public TransLog() {
    }

    private int x;
    private int y;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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