Abap类包装通用表

时间:2016-03-02 14:10:02

标签: sap abap

我想构建一个包装任意内部表的容器ABAP类。

我最初的方法是定义TYPE REF TO DATA的成员变量,并将引用传递给构造函数。

问题是由于指针,实例仍依赖于原始itab。因此,如果原始表从内存中释放,则无法再访问数据。我需要有一个存储在对象中的表数据的真实副本,所以我可以将对象传递到itab的原始范围之外。

有没有办法在ABAP中实现这一目标?

示例代码,其引用在最后定义的场景中崩溃:

CLASS lcl_test_itab_wrapper DEFINITION
  LOCAL
  FINAL
  CREATE PUBLIC.

  PUBLIC SECTION.
    CLASS-METHODS:
      access_outside_itab_scope.

    METHODS:
      constructor
        IMPORTING
          itab TYPE table,

      access_itab_data.

  PROTECTED SECTION.

  PRIVATE SECTION.
    CLASS-METHODS:
      sample_itab_setup
        RETURNING VALUE(result) TYPE REF TO lcl_test_itab_wrapper.

    DATA:
          table_ref TYPE REF TO data.
ENDCLASS.



CLASS lcl_test_itab_wrapper IMPLEMENTATION.


  METHOD access_itab_data.
    FIELD-SYMBOLS <table> TYPE table.
    ASSIGN me->table_ref->* TO <table>.

    WRITE:/ lines( <table> ).
  ENDMETHOD.


  METHOD constructor.
    me->table_ref = REF #( itab ).
  ENDMETHOD.


  METHOD sample_itab_setup.
    DATA:
      dummy_itab   TYPE TABLE OF string.

    APPEND 'test_record' TO dummy_itab.

    CREATE OBJECT result EXPORTING itab = dummy_itab.
  ENDMETHOD.

  METHOD access_outside_itab_scope.
    DATA(o_instance) = sample_itab_setup( ).

    " Here it crashes as the referenced itab was freed already.
    " I'd need to have a real itab copy stored in the instance
    o_instance->access_itab_data( ).
  ENDMETHOD.

更新:解决方案基于@vwegert回答

将构造函数引用赋值替换为:

CREATE DATA me->table_ref LIKE itab.
FIELD-SYMBOLS <table> TYPE table.
ASSIGN me->table_ref->* TO <table>.
<table> = itab.

2 个答案:

答案 0 :(得分:2)

您需要动态创建数据对象,而不是使用静态定义的数据对象(ab)。检查documentation of the CREATE DATA statement

答案 1 :(得分:0)

查看&#34;将xx引用到xx&#34;声明,您可以保存三行代码。