Posted on Mar. 31, 2010 at 08.45 PM - Kuala Lumpur, Malaysia
Sometimes there is a requirement to create a generic program to trigger ABAP proxy dynamically, so that we don't have to keep changing the program whenever we develop new proxy interfaces. How do we achieve that?
1. Create a custom table to store the relationship of interface ID with the proxy class and name
Notes: PROGTYPE is populated with proxy class name and PROGRAMNAME is populated with method name
*) We don't actually need to store the method name if we standardize its name during proxy creation
**) We don't even need a custom table to store this whole relationships if we standardize the repository object names
2. Create ABAP program to call the proxy method dynamically
a) Select the entry from the custom table based on the interface ID
b) Get method parameters from SAP standard table seosubco
* local data declaration
DATA: lt_para_tab TYPE abap_parmbind_tab.
DATA: lt_parameters TYPE gty_tt_parameters.
* get the method parameters
SELECT sconame INTO TABLE lt_parameters
FROM seosubco
WHERE clsname EQ gs_interface-progtype "class
AND cmpname EQ gs_interface-programname "method
AND scotype EQ '0'. "parameter
c) Populate method parameters with the reference variable values
* local data declaration
DATA: ls_parameters TYPE gty_parameters.
DATA: ls_para_tab TYPE abap_parmbind.
* populate the parameters of the method dynamically
LOOP AT lt_parameters INTO ls_parameters.
* get parameter's name
ls_para_tab-name = ls_parameters-sconame.
* get parameter's type
IF ls_parameters-sconame(2) = 'IP'.
ls_para_tab-kind = cl_abap_objectdescr=>exporting.
ELSE.
ls_para_tab-kind = cl_abap_objectdescr=>importing.
ENDIF.
* get the address of the parameters
CASE ls_parameters-sconame.
WHEN 'EP_ERRORCODE'.
GET REFERENCE OF gv_errorcode INTO ls_para_tab-value.
WHEN 'EP_ERRORTEXT'.
GET REFERENCE OF gv_errortext INTO ls_para_tab-value.
WHEN 'IP_AS_OF_DATE'.
GET REFERENCE OF p_date INTO ls_para_tab-value.
...
ENDCASE.
INSERT ls_para_tab INTO TABLE lt_para_tab.
ENDLOOP.
d) Check whether it is static or instance level method
* instantiate the class?
SELECT mtddecltyp INTO lv_method_type
FROM seocompodf UP TO 1 ROWS
WHERE clsname EQ gs_interface-progtype
AND cmpname EQ gs_interface-programname.
ENDSELECT.
e) Execute the method dynamically
* This is an instance method, instantiate the class
TRY.
CREATE OBJECT lo_interface TYPE (gs_interface-progtype).
CATCH cx_sy_dyn_call_error INTO lo_exception.
PERFORM display_exception USING lo_exception.
EXIT.
ENDTRY.
* call the instance method
TRY.
CALL METHOD lo_interface->(gs_interface-programname)
PARAMETER-TABLE
lt_para_tab.
CATCH cx_ai_system_fault INTO lo_exception.
PERFORM display_exception USING lo_exception.
EXIT.
ENDTRY.
In this blog, I don't include the codes on how to call static method, but it can be done pretty easy too :)
Life is beautiful! Let's make it meaningful and colorful!