简体   繁体   中英

How can I define a filled structure/table as class constant in ABAP Objects

I want to have an immutable predefined table as class variable. How do I define such a variable?

This is an old question, with a simple answer: Just create a static method (getter) that returns constant data.

Instead of using:

data(ls_sample) = lcl_myclass=>cs_data.

Use:

data(ls_sample) = lcl_myclass=>cs_data( ).

我将创建一个属性并将其标记为“只读”,您可以通过构造函数或使用Set-Method进行设置。

You cannot do like this using class constants in ABAP. The documentation explicitly says that:

  • You can specify a start value val for the ABAP types string and xstring only.

  • Constant internal tables, reference variables, and structures with not purely character-like flat components can be assigned their initial value by IS INITIAL only, and are therefore always initial.

As Tapio suggested, your only choice is read-only attributes, and I also suggest you to use static attributes, which can be initialized in constructor.

For example

CLASS lcl_test DEFINITION.
  PUBLIC SECTION.
  CLASS-DATA: itab TYPE RANGE OF i READ-ONLY.
  METHODS:
      constructor.
ENDCLASS.
CLASS lcl_test IMPLEMENTATION.
  METHOD constructor.
      itab = VALUE #( sign = 'I'  option = 'BT' ( low = 1  high = 10 )
                                                ( low = 21 high = 30 )
                                                ( low = 41 high = 50 )
                                  option = 'GE' ( low = 61 )  ).
  ENDMETHOD.
ENDCLASS.

One thing that after all that time would be a workaroud is the following:

  • Create your list
  • serialize it and save it as a read-only string
  • create a getter that deserializes it

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