如何从静态方法调用类构造函数?

时间:2019-04-26 06:53:32

标签: sap abap

在我的代码中,我想从静态方法CLASS_CONSTRUCTOR中调用ADD_BOOK方法。

但是我收到此语法错误:

  

不直接调用特殊方法“ CLASS_CONSTRUCTOR”   可能。

代码如下:

CLASS lcl_books DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS class_constructor.
    CLASS-METHODS add_book.
    ...
ENDCLASS.

CLASS lcl_books IMPLEMENTATION.
  METHOD class_constructor.
    SELECT * FROM zgib_bmabuecher INTO TABLE gt_return.
  ENDMETHOD.

  METHOD add_book.
    DATA lf_check TYPE n VALUE 0.
    LOOP AT gt_return INTO mf_books.
      IF if_book-isbn = mf_books-isbn.
        lf_check = 1.
      ENDIF.
    ENDLOOP.
    IF lf_check = 0.
      INSERT zgib_bmabuecher FROM if_book.
    ENDIF.
    lcl_books=>class_constructor( ).
  ENDMETHOD.

ENDCLASS.

1 个答案:

答案 0 :(得分:7)

您在错误消息中拥有所有信息。您不能(德语:darfst nicht)显式调用类构造函数。每当第一次使用该类时,它总是被自动调用一次。

如果要重用类构造函数的编码,则将其放在另一个类方法中,例如这样。

CLASS lcl_books DEFINITION.
  "...
  PRIVATE SECTION.
    CLASS-METHODS:
      select_books.
  "...
ENDCLASS.

CLASS lcl_books IMPLEMENTATION.
  METHOD class_constructor.
    select_books( ).
  ENDMETHOD.

  METHOD select_books.
    SELECT * FROM zgib_bmabuecher INTO TABLE gt_return.
  ENDMETHOD.

然后将您的add_book方法更改为

METHOD add_book.
    DATA lf_check TYPE n VALUE 0.
    LOOP AT gt_return INTO mf_books.
      IF if_book-isbn = mf_books-isbn.
        lf_check = 1.
      ENDIF.
    ENDLOOP.
    IF lf_check = 0.
      INSERT zgib_bmabuecher FROM if_book.
    ENDIF.
    select_books( ).
  ENDMETHOD.

ENDCLASS.