使用 CL_ABAP_CORRESPONDING 映射结构中不同级别的字段

Use CL_ABAP_CORRESPONDING to map fields on diffrent levels in a structure

我有两个嵌套结构,我想根据一些规则在运行时映射字段。可以附加 dest 结构的字段和 source 结构在嵌套结构的不同级别上。

(结构有不同的类型)

比如我要映射:

struct1-a1 = struct2-bsub1-s1_b1.
struct1-asub1-s1_a1 = struct2-b1.
    DATA:
      BEGIN OF struct1,
        a1 TYPE string VALUE 'a1',
        a2 TYPE string VALUE 'a2',
        a3 TYPE string VALUE 'a3',
        a4 TYPE string VALUE 'a4',
        a5 TYPE string VALUE 'a5',
        BEGIN OF asub1,
          s1_a1 TYPE string VALUE 's1_a1',
          s1_a2 TYPE string VALUE 's1_a2',
          s1_a3 TYPE string VALUE 's1_a3',
        END OF asub1,
      END OF struct1,

      BEGIN OF struct2,
        b1 TYPE string VALUE 'b1',
        b2 TYPE string VALUE 'b2',
        b3 TYPE string VALUE 'b3',
        a4 TYPE string VALUE 'b4',
        a5 TYPE string VALUE 'b5',
        BEGIN OF bsub1,
          s1_b1 TYPE string VALUE 's1_b1',
          s1_b2 TYPE string VALUE 's1_b2',
          s1_b3 TYPE string VALUE 's1_b3',
        END OF bsub1,
      END OF struct2.

我发现这个很酷 class 可以为字段构建映射,但它只有一个级别参数。

我的问题是我可以使用 the class CL_ABAP_CORRESPONDING 来映射不同级别的字段吗?我该怎么做。

不可以,映射的结构必须在同一层级。 class 文档摘录:

Notes

Components can only be mapped to each other if they are on the same level. Components in a substructure cannot be assigned to the components at higher levels, nor higher level components to components in a substructure.

你必须分成几个执行:

cl_abap_corresponding=>create(
      source            = struct2-bsub1
      destination       = struct1
      mapping           = VALUE cl_abap_corresponding=>mapping_table(
                          ( level = 0 kind = 1 srcname = 's1_b1' dstname = 'a1' ) )
      )->execute( EXPORTING source      = struct2-bsub1
                  CHANGING  destination = struct1 ).

cl_abap_corresponding=>create(
      source            = struct2
      destination       = struct1-asub1
      mapping           = VALUE cl_abap_corresponding=>mapping_table(
                          ( level = 0 kind = 1 srcname = 's1_a1' dstname = 'b1' ) )
      )->execute( EXPORTING source      = struct2
                  CHANGING  destination = struct1-asub1 ).

编辑:虽然文档看起来很简单,但我发现组件选择器可以在 SRCNAME 组件内部使用,以引用嵌套结构中的组件,例如上面的第一次执行等同于此代码(差异在 source = struct2srcname = 'bsub1-s1_b1' 中):

cl_abap_corresponding=>create(
      source            = struct2
      destination       = struct1
      mapping           = VALUE cl_abap_corresponding=>mapping_table(
                          ( level = 0 kind = 1 srcname = 'bsub1-s1_b1' dstname = 'a1' ) )
      )->execute( EXPORTING source      = struct2
                  CHANGING  destination = struct1 ).

似乎仍然不可能的是在DSTNAME组件中使用组件选择器,例如第二次执行不能表示destination = struct1dstname = 'asub1-b1',会出现异常