ABAP顾问
分类:
2009-08-18 12:41:36
ABAP中的动态编程(1): Run Time Type Services(RTTS)
ABAP的RTTS主要通过一些type classes来实现,包括RTTC(Run Time Type Creation)和RTTI(Run Time Type Identification)功能。需要注意的是ABAP不能在运行时修改type,不像主流动态编程语言(Python、Ruby...)那样。下面是这些type classes的继承关系。
CL_ABAP_TYPEDESCR
|
|--CL_ABAP_DATADESCR
| |
| |--CL_ABAP_ELEMDESCR
| |--CL_ABAP_REFDESCR
| |--CL_ABAP_COMPLEXDESCR
| |
| |-- CL_ABAP_STRUCTDESCR
| |--CL_ABAP_TABLEDESCR
|
|--CL_ABAP_OBJECTDESCR
|
|--CL_ABAP_CLASSDESCR
|--CL_ABAP_INTFDESCR
看到这个图的时候需要对ABAP的type system有一些了解。ABAP的type system正是分成data type和object type,然后data type又分成elementary type、reference type和complex type。这些在ABAP的帮助文档里面都有详述。简单的看几个RTTS的例子吧。
1. 获取一个structure的所有fields:
DATA:
lo_struct TYPE REF TO cl_abap_structdescr,
lt_comptab TYPE cl_abap_structdescr=>component_table,
ls_flight TYPE sflight.
FIELD-SYMBOLS:
lo_struct ?= cl_abap_structdescr=>describe_by_data( ls_flight ).
lt_comptab = lo_struct->get_components( ).
LOOP AT lt_comptab ASSIGNING
WRITE
ENDLOOP.
2. 创建一个structure:
TYPES: BEGIN OF s_field,
name TYPE fieldname,
dataelement TYPE field_type,
END OF s_field.
DATA:
lo_descr TYPE REF TO cl_abap_typedescr,
lt_comptab TYPE cl_abap_structdescr=>component_table,
ls_compfld TYPE cl_abap_structdescr=>component,
lo_struct TYPE REF TO cl_abap_structdescr,
ls_field TYPE s_field,
lt_field TYPE TABLE OF s_field,
lr_data TYPE REF TO data.
FIELD-SYMBOLS:
ls_field-name = 'CARRID'.
ls_field-dataelement = 'S_CARR_ID'.
APPEND ls_field TO lt_field.
ls_field-name = 'CONNID'.
ls_field-dataelement = 'S_CONN_ID'.
APPEND ls_field TO lt_field.
LOOP AT lt_field INTO ls_field.
CALL METHOD cl_abap_elemdescr=>describe_by_name
EXPORTING
p_name = ls_field-dataelement
RECEIVING
p_descr_ref = lo_descr
EXCEPTIONS
type_not_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
CONTINUE.
ENDIF.
CLEAR ls_compfld.
ls_compfld-name = ls_field-name.
ls_compfld-type ?= lo_descr.
APPEND ls_compfld TO lt_comptab.
ENDLOOP.
*create a structure
lo_struct = cl_abap_structdescr=>create( p_components = lt_comptab ).
*create data using the stucture
CREATE DATA lr_data TYPE HANDLE lo_struct.
ASSIGN lr_data->* to
ASSIGN COMPONENT 'CARRID' OF STRUCTURE
*assgin value to CARRID field
WRITE