接上一部分,继续探讨ABAP中的动态编程。
有时候,我们的ABAP程序本身就是动态创建的(特别是当我们不想物理地创建ABAP objects时),这时候,学习动态创建Subroutine甚至动态创建ABAP程序,就变得有必要。当然,正如有朋友说的那样,使用这样的动态后,我们无法使用where-used这样的功能,于SAP标准有背。
一. 【动态编程】动态创建Subroutine
测试程序:
*&———————————————————————* *& Report ZTEST_TRANSIENT_SUBROUTINE *& *&———————————————————————* REPORT ZTEST_TRANSIENT_SUBROUTINE. DATA: code type TABLE OF string, subrtnm(10) type c, prog type program, msg(20) type c, line(10) type c, word(10) type c, off(3) type c, lw_string type string. “ for concatenate
* prepare the ”Dynamic Subroutine sentence” append ‘PROGRAM SUBPOOL.’ to code. subrtnm = ‘TEST’. CONCATENATE ‘FORM’ subrtnm ‘.’ into lw_string SEPARATED BY space. “CONCATENATE ’FORM’ ’TEST’ ’.’ into lw_string SEPARATED BY space. APPEND lw_string to code. append ‘Write:/10 ”This is one transient subroutine”.’ to code. APPEND ‘ENDFORM.’ to code. * create subroutine dynamically GENERATE SUBROUTINE POOL code NAME prog MESSAGE msg LINE line WORD word OFFSET off. IF sy-subrc <> 0 . write:/ ‘Error occurs in line:’,line, / msg, /‘Word:’, word, / ‘Offset:’, off. ENDIF. * call the subroutine dynamically PERFORM (subrtnm) IN PROGRAM (prog).
结果:
二. 【动态编程】动态创建Program in Program
测试程序:
*&———————————————————————* *& Report ZTEST_TRANSIENT_PROGRAM *& *&———————————————————————* REPORT ZTEST_TRANSIENT_PROGRAM. DATA: code type TABLE OF string, prgnm(10) type c, lw_string type string. “ for concatenate prgnm = ‘ZTEST_SUB’. * form the dynamic-program CONCATENATE ‘PROGRAM’ prgnm ‘.’ INTO lw_string SEPARATED BY space. APPEND lw_string to code. APPEND ‘WRITE:/10 ”Hello, this is the transient program!”.’ to code. INSERT REPORT prgnm from code. * call the transiet program SUBMIT (prgnm) AND RETURN. * append the transient program READ REPORT prgnm into code. APPEND ‘WRITE:/10 ”Hello, this is the transient program! 2nd Time append.”.’ to code. INSERT REPORT prgnm from code. GENERATE REPORT prgnm. * call the transiet program SUBMIT (prgnm) AND RETURN.
结果:
第一次:
点击回退后:
文中用到的ppt文档(ABAP动态编程--官方资料),下载地址: