Question:
Hi,
I'm trying to stick to encapsulation rules and instead of creating a lot of methods "get_this", "get_that" "get_...", I'm trying to find a vay to create a generic get_field method (with a returning value).
E.G. suppose I have a class ZCL_MATERIAL which has an attribute l_mara type mara.
I would like to create a method so I can use it like:
data: my_material type matnr.
[...]
my_material ?= ZCL_MATERIAL->get_field( 'MATNR' ).
Do you think this is possible in ABAP? I'm facing the problem that the returning value has to be a defined data type (TYPE ANY or TYPE DATA cannot be used).
Any suggestion?
Many thanks,
Lorenzo
Answer:
the only solution I have found so far, use EXPORTING xxx type DATA instead of RETURNING.
I don't like it very much but it seems it is working:
CLASS materiale DEFINITION.
PUBLIC SECTION.
METHODS: set IMPORTING l_matnr TYPE matnr,
get_field IMPORTING l_field TYPE fieldname
EXPORTING l_value TYPE data.
PRIVATE SECTION.
DATA: l_mara TYPE mara.
ENDCLASS. "materiale DEFINITION
CLASS materiale IMPLEMENTATION.
METHOD set.
SELECT SINGLE * FROM mara INTO l_mara WHERE matnr EQ l_matnr.
ENDMETHOD. "set
METHOD get_field.
CASE l_field.
WHEN 'MATNR'.
l_value = l_mara-matnr.
WHEN 'ERSDA'.
l_value = l_mara-ersda.
ENDCASE.
ENDMETHOD. "get_field
ENDCLASS. "materiale IMPLEMENTATION
DATA: my_material TYPE REF TO materiale.
DATA: matcode TYPE matnr,
mydate TYPE laeda.
PARAMETER: p_matnr LIKE mara-matnr.
START-OF-SELECTION.
CREATE OBJECT my_material.
my_material->set( p_matnr ).
my_material->get_field( EXPORTING l_field = 'MATNR' IMPORTING l_value = matcode ).
my_material->get_field( EXPORTING l_field = 'ERSDA' IMPORTING l_value = mydate ).
Suggestions?
Answer:
A little step ahed:
METHOD get_field.
FIELD-SYMBOLS: <content> TYPE data.
ASSIGN COMPONENT l_field OF STRUCTURE l_mara TO <content>.
l_value = <content>.
ENDMETHOD. "get_field
so I can use whatever field of l_mara. But I'm still wondering if i'm on the right way...
Answer:
Thanks for keeping us posted Lorenzo.
The only realy way to access a structures field in a dynamic way is with field symbols so yes, you are heading in the right direction.
_________________
Regards
R
Abap KC
SFMDR
Answer:
I have to admit, having to code a large number of getter and setter methods everytime I create a class drives me round the bend...
I use Eclipse for Portals / general Java development and that has a menu option to create all getter and setter methods for you in a class based on the data declarations in your class.
I really wish SAP would add something like that to SE24...
Answer:
I really wish SAP would add something like that to SE24...
Hey!
Job for you - Write it yourself!
_________________
Regards
R
Abap KC
SFMDR
Answer:
Shush! My manager might see this...