Dynamic method

Hi SAP Gurus,
Is it is possible to pass the name of method during run time, actually I have 10 methods with same import, export
I need to make one single report which will get the name of method during run time.
CALL METHOD detail->CONTACT_DATA_OUT    "this name should be changed during run time.
     EXPORTING
          output = req.
Thanks,
Krishna

Sorry for ridiculous question, but did you pass your method name or just used that one literally : 'METHOD_NAME' ?
Refer this snippet:
PARAMETERS pa_meth(61) TYPE c.
CLASS lcl_test DEFINITION.
  PUBLIC SECTION.
    METHODS: start, end.
ENDCLASS.             
CLASS lcl_test IMPLEMENTATION.
  METHOD start.
    WRITE: 'This is the START method called dynamically'.
  ENDMETHOD.                    "start
  METHOD end.
    WRITE: 'This is the END method called dynamically'.
  ENDMETHOD.                    "end
ENDCLASS.                
START-OF-SELECTION.
  DATA: r_test TYPE REF TO lcl_test,
       r_classdescr TYPE REF TO cl_abap_classdescr.
  r_classdescr ?= cl_abap_typedescr=>describe_by_name( 'LCL_TEST' ).
  READ TABLE r_classdescr->methods WITH KEY name = pa_meth TRANSPORTING NO FIELDS.
  IF sy-subrc <> 0.
    WRITE: 'Method', pa_meth, 'doesn''t exist'.
  ELSE.
    CREATE OBJECT r_test.
    CALL METHOD r_test->(pa_meth).
  ENDIF.
Regards
Marcin

Similar Messages

  • Dynamic method calls in bounded task flows?

    Hi!
    I have the following scenario:
    We are developing a framework in which we would include modules as ADF libraries (as JAR files) with bounded task flows. This framework contains a bean class with bindings for some UI components in framework which I enable or disable (depends on user action). That is the main reason bean class should be present in framework application.
    I have a bounded task flow in every module which needs to call a method in bean with UI component's bindings that would enable or disable that component.
    How can I achieve that? To pass bean as a parameter into bounded task flow and then call its methods? That is dynamic method calls for bean.
    I'm using JDeveloper 11.1.2.1.0
    Thanks for your help
    Regards, Marko

    Hi,
    I explained this; +"I have a bounded task flow in every module which needs to call a method in bean with UI component's bindings that would enable or disable that component. How can I achieve that? To pass bean as a parameter into bounded task flow and then call its methods?"+ a couple of times already (not sure if it was all for you) and don't think I change my position here. I also explained how to use a ValueExpression to lookp a managed bean containing component bindings (should be in requestscope).
    Frank

  • Type conflict during dynamic method call.

    While executing the following program I get the error "Type conflict during dynamic method call.":
    DATA: container_r  TYPE REF TO object,
          grid_r       TYPE REF TO object,
          itab_saplane TYPE TABLE OF saplane.
    * IMPORTANT NOTE: class names must be in UPPER CASE
    DATA: str_cnt TYPE seoclsname VALUE 'CL_GUI_CUSTOM_CONTAINER',
          str_gui TYPE seoclsname VALUE 'CL_GUI_ALV_GRID',
          meth_name TYPE STRING VALUE 'SET_TABLE_FOR_FIRST_DISPLAY'.
    TYPE-POOLS abap.
    DATA: ptab    TYPE abap_parmbind_tab,
          wa_ptab LIKE LINE OF ptab,
          ref     TYPE REF TO data.
    CREATE OBJECT container_r TYPE (str_cnt)
      EXPORTING container_name = 'CUSTOM_CONTROL1'. " Name of the custom control area (UC!)
    * Construct parameter itab
    GET REFERENCE OF container_r INTO ref.
    wa_ptab-name  = 'I_PARENT'.  " Must be upper-case
    wa_ptab-value = ref.
    INSERT wa_ptab INTO TABLE ptab.
    *   EXPORTING i_parent = container_r.
    CREATE OBJECT grid_r TYPE (str_gui)
      PARAMETER-TABLE ptab.
    SELECT * FROM saplane INTO CORRESPONDING FIELDS OF TABLE itab_saplane.
    * Cannot call set_table_for_first_display directly...
    CALL METHOD grid_r->(meth_name)
      EXPORTING I_STRUCTURE_NAME = 'SAPLANE'  " Type of the rows in the internal table  (UC!)
      CHANGING  IT_OUTTAB = itab_saplane.     " The internal table itself
    CALL SCREEN 100.
    Any help would be appreciated!

    Hi ...
    Apologies ... for confusion ... actually both are required ...
    the type 'E' as well as CL_GUI_CONTAINER.
    The below code worked for me ...
    check out how I cast it to the parent class type ...
      DATA : lv_container   TYPE seoclsname VALUE 'CL_GUI_CUSTOM_CONTAINER',
             lv_control     TYPE seoclsname VALUE 'CL_GUI_ALV_GRID',
             lv_method      TYPE string VALUE 'SET_TABLE_FOR_FIRST_DISPLAY',
             lt_par_tab     TYPE abap_parmbind_tab,
             ls_param       LIKE LINE OF lt_par_tab,
             lref_cont      TYPE REF TO cl_gui_container,
             lv_data        TYPE REF TO data.
    CREATE OBJECT lref_container
          TYPE
            (lv_container)
          EXPORTING
            container_name = 'ALV_AREA'.
        ls_param-name = 'I_PARENT'.
        ls_param-kind = 'E'.
        lref_cont ?= lref_container.
        GET REFERENCE OF lref_cont INTO lv_data.
        ls_param-value = lv_data.
        INSERT ls_param INTO TABLE lt_par_tab.
    **  Now create ALV Control.
        CREATE OBJECT lref_alv_ctrl
          TYPE
            (lv_control)
          PARAMETER-TABLE
            lt_par_tab.
    **  Set table for 1st display
        DATA : lv.
        lv = lref_alv_ctrl->mc_fc_print.
        CALL METHOD lref_alv_ctrl->(lv_method)
          EXPORTING
            i_structure_name = 'T001'
          CHANGING
            it_outtab        = lt_company.
    Cheers
    Edited by: Varun Verma on Aug 12, 2008 4:19 PM

  • Hi,i am trying to edit a BP and i get this error;An attempt was made to execute a dynamic method callon an initial(NULL-) object reference. The reference must refer to an object. what could be missing?

    BP_....AccountActivitiesOV.htm....application BPBT.
    what could be wrong? An attempt was made to execute a dynamic method callon an initial(NULL-) object reference. The reference must refer to an object???

    Hi Dunamis,
    Please check if below links can help you;
    Error on execution of Web Interface
    Help! I meet this Business Server Page (BSP) error CX_SY_REF_IS_INITIAL
    Strange Error in Transformation of 2LiS_03_BF with 0IC_C03
    Regards,
    Kamfrk.

  • Working with class based exception and dynamic method calls

    Hi Gurus,
    we just changed out ERP from EHP6 to EHP7.
    Since we did so we are facing an issue with an Z-Report we are using quite often.
    This reports looks up Workitems and executes the according methods so that we can go into debugging if we were facing any problems or errors.
    since the EHP Upgrade this statement has problems:
      data:        lt_parmbind   type abap_parmbind_tab,         lt_excpbind   type abap_excpbind_tab,         lo_runtime    type ref to object.     call method lo_runtime->(iv_cls_method)       parameter-table       lt_parmbind       exception-table       lt_excpbind.this CALL METHOD Statement has Problem with the Exception Table. We are quite often getting DYN_CALL_METH_EXCP_NOT_FOUND short dumps with Exception "CX_SY_DYN_CALL_EXCP_NOT_FOUND".
    The system has problems handling the content of lt_excpbind. if i clear this table the CALL METHOD statement works fine.
    AS an example we are trying to call /IDXGC/CL_PD_PROCESS_STEPS-->CREATE_DATA. This method has 2 exceptions
    /IDXGC/CX_PROCESS_ERROR
    Process Layer Exception
    CX_BO_TEMPORARY
    Temporary Business Exception
    The Content of LT_EXCPBIND is
    INDEX
    NAME
    VALUE
    2
    /IDXGC/CX_PROCESS_ERROR
    1
    2
    CX_BO_TEMPORARY
    2
    From my point of view the Problem ist, that they are marked as "class based". I think so because if you looked up the SAP Help for the EXCEPTION-TABLE Statement it is written that is statement only works for none-classbased exception.
    I think that restriction is quiet clear. But what i am wondering about is.. that restriction also exists for EHP6. And in EHP6 it work. Does anyone know why? Or how i can change me CALL METHOD Statement that i will work again?
    Best Regards
    Udo

    Class-based exceptions must be caught using try/catch statement.
    Calling dynamically a method catchable exceptions are:
    CX_SY_DYN_CALL_EXCP_NOT_FOUND
    CX_SY_DYN_CALL_ILLEGAL_CLASS 
    CX_SY_DYN_CALL_ILLEGAL_METHOD
    CX_SY_DYN_CALL_PARAM_MISSING 
    CX_SY_DYN_CALL_PARAM_NOT_FOUND 
    CX_SY_REF_IS_INITIAL
    Anyway catching cx_root (as shown by Matthias) will catch everything is catchable.

  • Dynamic Method call with CHANGING

    Hi,
    I have the following method call:
          CALL METHOD o_salv->DISPLAY_SALV
            CHANGING
              it_data = it_ekko.
    I would like to make this dynamic so that I can call it multiple times from my program with the came set of code.
    I have this working for other Method calls, but the use the same parameters on both sides such as:
          CALL METHOD o_main->get_date
            IMPORTING
              it_ekko = it_ekko.
    being coded as such:
          CALL METHOD o_main->(v_method)
            PARAMETER-TABLE
              ptab.
    Can someone please give me some guidance on how to code the top example dynamically when the 2 variables are different?
    Hope that makes sense...thanks for your help!
    Andy

    Hello Bjorn
    I would suggest the following approach:
    (1) Collect all your GUI control instances in an itab whose line type is TYPE REF TO cl_gui_control.
    (2) Define your "free" method:
    LOOP AT mt_gui_controls INTO lo_gui_control.
    * See if gui control was text editor
      TRY.
        lo_textedit ?= lo_gui_control.
      CATCH cx_sy_move_cast_error INTO lo_error.
      ENDTRY.
      IF ( lo_error IS NOT BOUND ).
        lo_textedit->free.
    *   ... your coding
        CONTINUE.
      ENDIF.
    * See if gui control was tree
      TRY.
        lo_tree ?= lo_gui_control.
      CATCH cx_sy_move_cast_error INTO lo_error.
      ENDTRY.
    ENDLOOP.
    The FREE methods are redefined in the subclasses. However, you could try to call lo_gui_control->free directly because I am not sure if the coding of the superclass or subclass is called (I cannot test this at the moment).
    Regards
      Uwe

  • Problem in dynamic method execution???????

    Hi,
    I am facing the problem in selecting the method at run time.
    I have a class with methods like myMethod1,myMethod2,myMethod3,myMethod4....
    In my program I am receiving a parameter. for e.g. "2"
    Then I want to execute myMethod2.
    I am doing it this way "myMethod"+"2"+"()". But its not working .
    Canany body help me out.
    Thanks in Advance

    To expand on schapel.
    myObject.getClass().getMethod("myMethod2", new Class[0]).invoke(myObject, new Object[0]);will invoke the method called "myMethod2" on the Object myObject. The Class[] and Object[] arrays hold the ordered parameter types and values for the method respectively. In this case, myMethod2 is assumed to have no parameters.
    Primitive parameters/return values in the reflection API are replaced by their wrapper classes. As an example, if I have a method called getInt on the class MyClass that takes a float and returns an int, then you would invoke it thus:
    Integer i = new Integer(12);
    Method m = MyClass.class.getMethod("getInt", new Class[]{ Float.TYPE });
    Float float = (Float)m.invoke(myClassInstance, new Object[]{ i });
    Float f = float.floatValue();When dynamically invoking a static method, you can supply null as the instance upon which to invoke the method

  • Dynamic method call

    Hello Gurus,
    is there any possibility to write something like this in ABAP ??
      CALL METHOD zz_but050=>get_but050
        EXPORTING
        IF X = 1.  i_var_partner1 = l_var_partner1 ENDIF.
        IF X = 2.  i_var_partner2 = l_var_partner2 ENDIF.
        IMPORTING
          e_tab_but050   = l_tab_but050
        EXCEPTIONS
          keine_daten    = 1.
    Best regards,
    Ioan Constantin.

    Yes there is. The simplest would be
    data: lv_partner  type ...
    IF X = 1.  lv_partner = l_var_partner1 ENDIF.
    IF X = 2.  lv_partner = l_var_partner2 ENDIF.
    CALL METHOD zz_but050=>get_but050
        EXPORTING
         i_var_partner1 = lv_partner
        IMPORTING
          e_tab_but050   = l_tab_but050
        EXCEPTIONS
          keine_daten    = 1.
    Or you can use dynamic form of CALL METHOD where you pass your parameters by means of PARAMETER-TABLE addition. Please refer [CALL METHOD|http://help.sap.com/abapdocu_70/en/ABAPCALL_METHOD_SHORTREF.htm] -> dynamic form.
    Regards
    Marcin

  • Trouble in dynamic method invocation

    hai forum,
    Your previous responses on this topic 'method invocation' has greatly helped me in writing a code to invoke method dynamically.As some experts pointed out,the parameters had to be type casted.
    Please help me out of my latest trouble.I invoke only a particular method 'methodName' of a particular calss instance 'instance'.But when i run the code Exceptions are thrown for all the methods of that class whereas i require exceptions connected with "methodName" only.
    I just could not figure out my mistake, so please help me out.
    Thank you.
        private class MethodInvoke implements ActionListener
            private String methodName=""; //name of the method
            Object instance;                          //instance of the class
            private int paraNum=0;             //num of parameters
            public void setParameters(String methodName,Object instance,int paraNum)
                this.methodName = methodName;
                this.instance=instance;
                this.paraNum=paraNum;
            public void actionPerformed(ActionEvent e)
                 try
                           //TAKE PARAMETERS FROM USER USING TEXTFIELDS INTO AN ARRAY LIST
                        Component[] cList = textfieldPanel.getComponents();
                        ArrayList parameterList = new ArrayList(paraNum);
                        Object[] parameters = new Object[parameterList.size()];
                         for (int x = 0; x < paraNum; x++)
                                if (cList[x] instanceof JTextField)
                                    String value = ((JTextField) cList[x]).getText(); 
                                    parameterList.add(value);
                        Method[] allMethods = instance.getClass().getMethods();
                        Method method = null;
                        for (int i = 0; i < allMethods.length; i++)
                                if (allMethods.getName().equals(methodName))
    method = allMethods[i];
    break;
    if (method == null)
    throw new RuntimeException("Method not found");
    Class[] types = method.getParameterTypes();
    for (int i = 0; i < paraNum; i++)
    String values = (String)parameterList.get(i);
    if (types[i].equals(Integer.class))
    parameters[i] = new Integer(values);
    else if (types[i].equals(Long.class))
    parameters[i] = new Long(values);
    else if (types[i].equals(String.class))
    parameters[i] = values;
    else if (types[i].equals(Float.class))
    parameters[i]=new Float(values);
    else if (types[i].equals(Boolean.class))
    parameters[i]=new Boolean(values);
    else
    System.out.println("Do not support the data type");
    Object result = method.invoke(instance, parameters);
    System.out.println("Invoked result: " + result);
    catch(Exception e3)
    System.out.println(e3);

    This is the Emp class which iam calling.Hope this will help you.
    import java.io.*;
    public class Emp
         private String designation;
         private int salary;
         private int id;
         private String name;
         public Emp()
         public void setId(int i)
              id=i;
         public int getId()
              return id;
         public void setDesignation(String d)
              designation=d;
         public void setName(String d)
              name=d;
         public void setSalary(int s)
              salary=s;
         public String getDesignation()
              return designation;
         public int getSalary()
              return salary;
         public String getName()
              return name;
         public void setAll()
              try
                   System.out.println("Enter name:");
                   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                   String n=br.readLine();
                   setName(n);
                   System.out.println("Enter ID:");
                   setId(Integer.parseInt(br.readLine()));
                   System.out.println("Enter Designation:");
                   n=br.readLine();
                   setDesignation(n);
                   //System.out.println("Enter Salary:");
                   //setSalary(Integer.parseInt(br.readLine()));
              catch(Exception e)
         public void getAll()
              System.out.println("Name: "+getName()+"\n ID: "+getId()+
                        "\n Designation: "+getDesignation());
         public void pay(int w)
              getAll();
              System.out.println("Name: "+name+"\nAmount to be paid : "+w);
         /*public static void main(String[] args)
              Emp e=new Emp();
              e.setAll();
              e.getAll();
    }

  • Dynamic method lookup

    Hi all
    Here is my code:
    class Superbase{void print(Superbase s){System.out.println("Super");}}
    class Base extends Superbase{void print(Base b){System.out.println("Base");}}
    class Derived extends Base{static void print(Derived d){System.out.println("Derived");}}
    class OverloadDemo{
    public static void main(String[] args){
      Superbase a = new Superbase();
      Superbase b = new Base();
        Derived c = new Derived();
           a.print(new Superbase()); b.print(new Base()); c.print(new Derived());
    }a,b,c denore objects of Superbase, Base, and Derived classes respectively. According to me it should print "Super Base Derived". But, it's printing "Super Super Base"
    can you explain ....why is it so?
    Thanks

    are all the methods static or just the last one? (i.e. a typo in your post)

  • Dynamic method signatures

    This does not compile:
    public class Main {
      public static void main(String[] args) {
        Object sok = Socket.class.newInstance();
        foo(sok); // syntax error only as help to prevent runtime errors?
        Object x = ArrayList.class.newInstance();
        foo(x);  // syntax error because method linkage must happen and i don't know the class of "x" yet.
      public static void foo(Socket s) { println("i am a socket");  }
      public static void foo(List l) { println("i am a list"); }
    }Is the compiler complaining only to prevent a possible runtime (typecast) error? Or, is there actually some real problem (perhaps method linkage)?
    I read that methods live in their own special place in memory (and each has an address)? And is that address inserted into the bytecode when the Java source is compiled? So, while in the runtime every object knows its type, and this would enable selection of the correct method, you can't wait because of the need for compile-time method linking? Or, while waiting is technically possible, you can't because the developers of Java wanted to help developers to minimize run-time errors.
    If this question makes no sense, please help clear-up my misunderstanding about method linkage. thanks.

    dpxqb wrote:
    It only cares about the reference type of the expression you pass to foo(expression), which is Object for both cases.awesome. So, I hope this means that the "type" of the concrete object is not relevant for method signature. Rather, it is the "type" of the reference .Correct. I believe it's common to say class when talking about the concrete runtime object, and "type" when talking about the compile-time reference.
    And "reference typing" (aka "casting") happens at compile-time while "object typing" happens in the run-time.Yes and no. Your terminology is non-standard, so I'm not sure exactly what you mean, but approximately, yes, references types matter at compile time and object classes matter at runtime (for polymorphism in overridden methods, for example).
    Casting is both a compile-time and a runtime operation, however. At compile time, the reference type has to be one that could possibly be cast to whatever the target type is, and at runtime, the actual object has to be of an appropriate class for the cast to succeed.
    String s1 = (String)new Date(); // compile time error can't cast "across" the hierarchy
    String s2 = (String)new Object(); // compiles fine, but ClassCastException at runtime
    Object o1 = "abc";
    String s3 = (String)o1; // success

  • Dynamic method call needs reflection class?

    Hi,
    First of all, this is my first post so go easy on me ;)
    I would like to have something like this in Java:
    String name = "number1";
    int temp = name + getme();
    the integer temp should now be the result of the method "number1getme()".
    By changing the value of 'name' I could get the value of number2, number3 etc. etc.
    Hope you understand and can help.
    Yours Sincerely,
    GrandiJoos

    If you really want to do it this way, you will indeed need to use reflection. Have you considered other options, such as storing values in a Map or creating one getme() method that takes a name argument?Map<String, Integer> temps = new HashMap<String, Integer>();
    .. fill the map with temperatures
    String name="number1";
    int temp = temps.get(name);orString name="number1";
    public int getme(String name) {
    int result = ...;
    if(name.equals("number1")) {
      result = <some temp here>;
    return result;
    }

  • Information need on Dynamic Replenishment method

    Hi,
    Please provide your valuable inputs:
    1. Could you please let us know whether dynamic method can be used to replenish wh. If that is allowed please let us know why Order is not generated in that case or how it should be generated?
    Eg: Wh 's soh is zero, created replenishment for wh.
    2. Instead of dynamic i used 'Dynamic Issues' then order is generated successfully. If dynamic is not used for wh replenishment what is the reason behind that?
    Regards,
    Valli
    Edited by: user604995 on Aug 16, 2012 10:15 AM

    There are many notes and documents on MyOracleSupport on the topic of (Dynamic) (WH) replenishment, I suggest to find and read those first.
    Best regards,
    Erik

  • Object created dynamically. how to call a method or interface from it

    Hi Experts,
    I've just created an abap proxy dynamically
       FIELD-SYMBOLS <ref> TYPE any.
        CREATE DATA dref TYPE REF TO
                   (ld_class).
        ASSIGN dref->* TO <ref>.
        CREATE OBJECT <ref>
          TYPE
            (ld_class)
          EXPORTING
            logical_port_name =logicalport.
    This runs OK
    But I  can't call an Interface of the object proxy that belongs to ld_class
      ld_prot ?=   <ref>->if_proxy_basis~get_protocol( if_wsprotocol=>sequence ).
    because the object <ref> is type any, it doesen't runs
    This work' s fine
        MOVE  <ref> ?TO proxy1.
        ld_prot ?= proxy->if_proxy_basis~get_protocol( if_wsprotocol=>sequence )
    if proxy is explicity declarated like class proxy
    But I don't want do it. I want do it dynamically to avoid write data declaration explicity
    I think this is a problem for every data that must be declarated by the form TYPE REF TO
    What must I do ?
    thanks in advance.

    Hi.,
    Check this help Document : [Dynamic Method Call in ABAP Objects|http://help.sap.com/abapdocu_70/en/ABENNEWS-46-OBJECTS-DYNAMIC.htm]
    aslo  [Dynamic method call|Type conflict during dynamic method call.;
    hope this helps u.,
    Thanks & Regards
    Kiran

  • Calling A Super Method Externally

    Hi,
    I would like to call an overridden method, a super method, of an object externally. I thought all I needed to do was:
    1. get the java.lang.Class object of the super class where the original method was declared and implemented.
    2. get the appropriate java.lang.reflect.Method object from the Class object.
    3. override the java language protections on the Method object.
    4. Call Method.invoke() with the instance of the subclass which I wanted to call the method on.
    Unfortunately, when I got to step 4, I saw this in the documentation for Method.invoke:
    "If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, Second Edition, section 15.12.4.4; in particular, overriding based on the runtime type of the target object will occur."
    Is there any way to externally access the functionality of a super method implementation on a subclass that overrides it? It seems like there should be...
    In case you are wondering, the reason I am doing this is I am trying to implement a deep clone method. However, I would like any class to be able to call the deep clone method by passing themselves as an argument to a static method -- that way you don't have to worry about subclasses inheritting clone or anything like that. The code would look something like this (however it seems that according to the docs, this would result in an infinite recursion because when the Object.clone() method is invoked, it would actually resolve to the MyDeepCloneableObject.clone() method (which would call the utility function, which would invoke the Object.clone() again etc. etc.)):
    public class MyDeepCloneableObject implements Cloneable {
    public Object clone() {
    return ObjectUtil.deepClone(this);
    public class ObjectUtil {
    private static final Method OBJECT_CLONE_METHOD;
    private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
    private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
    static {
    //Set the OBJECT_CLONE_METHOD
    try {
    OBJECT_CLONE_METHOD =
    Object.class.getDeclaredMethod("clone", EMPTY_CLASS_ARRAY);
    OBJECT_CLONE_METHOD.setAccessible(true);
    } catch (NoSuchMethodException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    } catch (RuntimeException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    public static Object deepClone(Cloneable object, int levels) {
    Object clone;
    try {
    clone = OBJECT_CLONE_METHOD.invoke(object, EMPTY_OBJECT_ARRAY);
    } catch (IllegalAccessException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    } catch (InvocationTargetException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    } catch (RuntimeException e) {
    System.out.println(e.toString());
    e.printStackTrace();
    return null;
    // Use more reflection on fields of clone to implement deep clone
    }

    In your example the clone method is not creating a clone, just returning a new instance of an object of the same type. In both cases the default shallow clone method should be implemented as follows:
    public Object clone() {
    //Call Object.clone()
    return super.clone;
    By doing so, any subclasses will also have their fields copied when clone() is called.
    From the javadocs for Object.clone():
    "The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation."
    Now as to how the parent is supposed to know about fields in subclasses, the implementation of clone is implemented in a native method in Object, so the JVM can pretty much know anything about the subobject as long as it has a reference to it. Further, if I wanted to make my own implementation, I could using reflection:
    public Object clone() {
    // Get the runtime class of this object, note that the runtime class
    // may be a subclass of the class in which this clone method is defined
    Class objectClass = this.getClass();
    //Get all of the fields in this class and it's super classes
    List fieldsList = new ArrayList();
    while (objectClass != null) {
    Field[] fields = objectClass.getDeclaredFields();
    for (int j =0; j < fields.length; j++) {
    fieldsList.add(fields[j]);
    objectClass = objectClass.getSuperClass();
    //Now I can create a new instance of the runtime class and set
    //all of its fields appropriately
    However, I'm sure the JVM's implementation is far more efficient.
    I have not benchmarked serialization. However, all the steps in my procedure would have to be done for serialization anyway (i.e. get list of all fields, instantiate equivalent field values and set them in the new object), but serialization also needs to convert everything to a byte representation and then parse it out again. Furthermore, serialization will perform a fully deep clone, where as I only want a one level deep clone (or two depending on how you think of it -- i.e. not a shallow copy of references (as Object.clone(0 does), but a copy of direct fields and containers (i.e. Maps and Collections in fields should be cloned, but not objects in the Maps and Collections). So if an object has a field which is a List and the List field contains 1 entry, and the object is cloned, then subsequent modifications to the List field in the cloned object are not reflected in the original object's List field and vice versa (i.e. the 1 entry is removed in the original , but remains in the clone's version of the List field).

Maybe you are looking for

  • Run time exception

    Hi Friends, First i deleted the model and the model backend features had changed at the backend. and inported again.After importing the model when i tried to deploy and run the application i am getting the following exception: Tab512 is a structure i

  • Bit of a tricky one ....

    Ok, from my query I have this: 1,2,3,4,5,6,7,8,9 And I want to turn it into this <table> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> <td>6</td> <td>7</td> <td>8</td> <td>9</td> <td></td> </tr> </table> now if my list now grows t

  • How to display total for a column in updateble report

    How can I display total on a report column? the query is select htmldb_item.checkbox(1,invoice_id) invoice_id, htmldb_item.DISPLAY_AND_SAVE(2,invoice_no,15)invoice_no, htmldb_item.DISPLAY_AND_SAVE(3,to_char(invoice_date, 'DD-MON-YYYY'),20) invoice_da

  • Doubt in remote enabled module

    hi all i am creating a fn. module (rfc).when i activate the fn. module it shows an error (report/program statement missing or program type is include). my fn group is inactive how to active that ... is the problem is because of fn group....please hel

  • Troubles after installing Catalyst and re-installing KDE

    Hi everybody, when I was installing arch I was following the wiki and installed the open source driver xf86-video-ati and KDE (the last version in the repository). After that everything worked fine, until I heard about some nice games that run on Lin