How to use an output parameter in Java?

前端 未结 7 1233
天涯浪人
天涯浪人 2020-12-04 15:40

Could someone please give me some sample code that uses an output parameter in function? I\'ve tried to Google it but just found it just in functions. I\'d like to use this

7条回答
  •  攒了一身酷
    2020-12-04 15:51

    As a workaround a generic "ObjectHolder" can be used. See code example below.

    The sample output is:

    name: John Doe
    dob:1953-12-17
    name: Jim Miller
    dob:1947-04-18
    

    so the Person parameter has been modified since it's wrapped in the Holder which is passed by value - the generic param inside is a reference where the contents can be modified - so actually a different person is returned and the original stays as is.

    /**
     * show work around for missing call by reference in java
     */
    public class OutparamTest {
    
     /**
      * a test class to be used as parameter
      */
     public static class Person {
       public String name;
         public String dob;
         public void show() {
          System.out.println("name: "+name+"\ndob:"+dob);
       }
     }
    
     /**
      * ObjectHolder (Generic ParameterWrapper)
      */
     public static class ObjectHolder {
        public ObjectHolder(T param) {
         this.param=param;
        }
        public T param;
     }
    
     /**
      * ObjectHolder is substitute for missing "out" parameter
      */
     public static void setPersonData(ObjectHolder personHolder,String name,String dob) {
        // Holder needs to be dereferenced to get access to content
        personHolder.param=new Person();
        personHolder.param.name=name;
        personHolder.param.dob=dob;
     } 
    
      /**
       * show how it works
       */
      public static void main(String args[]) {
        Person jim=new Person();
        jim.name="Jim Miller";
        jim.dob="1947-04-18";
        ObjectHolder testPersonHolder=new ObjectHolder(jim);
        // modify the testPersonHolder person content by actually creating and returning
        // a new Person in the "out parameter"
        setPersonData(testPersonHolder,"John Doe","1953-12-17");
        testPersonHolder.param.show();
        jim.show();
      }
    }
    

提交回复
热议问题