【问题标题】:How to call parent methods in Java/Groovy如何在 Java/Groovy 中调用父方法
【发布时间】:2022-02-07 21:38:38
【问题描述】:

我是 Java 和 groovy 的新手,我主要使用 Python 编写代码。我试图理解为什么代码不起作用。 我得到的错误是 groovy.lang.MissingMethodException: No signature of method: static HelloWorld.TestingProduct() is applicable for argument types: () values: []

我的任务是在项目中添加 eventdate 作为 sysdate,我只是想了解如何通过本地测试来添加它

import groovy.transform.ToString
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter



public class HelloWorld{

     public static void main(String[] args){
        String testin = TestingProduct().Inventory()
        System.out.println(testin);
     }
}


class Parent {

   private String setDateNow() {
        OffsetDateTime now = OffsetDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        return formatter.format(now);
    }
}

class TestingProduct extends Parent {
   private static ProductInventoryEvent Inventory(){
      def invent = new ProductInventoryEvent(
         productId:'1',
         productIdType:'2',
         eventType:'3',
         eventDate: setDateNow(),
      )
      return invent
   }
}


@Canonical()
@ToString(includeNames = true)
class ProductInventoryEvent {
    String productId
    String productIdType
    String eventType
    String eventDate

}

【问题讨论】:

  • TestingProduct 是一个类。要创建新类,您必须使用 new 关键字:new TestingProduct()。没有new - 这是一个函数/方法调用。
  • 我试过 new ,现在我得到了 groovy.lang.MissingMethodException: No signature of method: static TestingProduct.setDateNow() is applicable for argument types: () values: []

标签: java date oop groovy


【解决方案1】:

您的代码中很少有错误的地方。让我先从HelloWorld 类开始。

您试图以错误的方式访问/调用TestingProduct 的静态方法Inventory。为了访问静态方法,您不需要该类的任何对象实例。所以,你应该使用TestingProduct.Inventory(),而不是TestingProduct().Inventory()

第二件事是,您的方法 Inventory() 返回 ProductInventoryEvent 而不是字符串。因此,您应该更改要初始化的变量的类型。下面是代码的样子:

public class HelloWorld {
    public static void main(String[] args){
      ProductInventoryEvent testin = TestingProduct.Inventory();
      System.out.println(testin);
    }
}

您应该更改的另一件事是TestingProduct 类中Inventory() 方法的访问修饰符。您应该使用包私有或公共访问修饰符,而不是私有。所以代码应该是这样的:

public class TestingProduct {
   static ProductInventoryEvent Inventory(){
      def invent = new ProductInventoryEvent(
            productId:'1',
            productIdType:'2',
            eventType:'3',
            eventDate: setDateNow(),
      )
      return invent;
   }
}

【讨论】:

  • 非常感谢您的帮助!
【解决方案2】:

我还认为,您不能在父类中调用私有方法。您必须将访问修饰符更改为受保护

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2012-08-09
    • 2013-11-02
    • 1970-01-01
    • 2018-09-09
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多