How can I pass an object to a function by value?

Hi
I have a function with an argument. this argument is an object. I don't want to alter this object. But java passes this object by reference and some fields in this object are altered after function return.
How can I pass this object by value and keep my original data unbroken?
thanks for any help

a.toraby wrote:
I have a function with an argument. this argument is an object. I don't want to alter this object. But java passes this object by reference and some fields in this object are altered after function return.
How can I pass this object by value and keep my original data unbroken?How you approach it is likely to depend on how much control you have over the code in question. If it's legacy code and has been badly designed, there's probably very little you can do to protect existing code short of a complete refactoring.
What you could do as an interim measure is:
1. Create an immutable wrapper to your existing mutable class.
2. Create new methods that replicate the existing ones, but take the immutable class instead.
3. Deprecate the old methods.
This won't break client code, but they will now get warnings when they compile and you can add documentation to point them to the new class/methods.
If you are in control of the code (especially if you're still in the design stages), you've got several options:
1. As Dr.Clap says, make your class immutable (probably best).
2. If this isn't possible, create mutable and immutable variants of your class. This is often best achieved by hanging them both from an interface.
Winston

Similar Messages

  • How can I pass variable to eventdriven startElement() function?

    I am new to java and SAX. Could anybody tell me how to pass variable to eventdriven startElement function? I tried the following code but didn't work.
    public class ReadXmlSax extends DefaultHandler
    String elementName;
    String requestName;
    Vector v = new Vector();
    public Enumeration getAttribute(String sFileName, String sTagName, String sAttrName)
         Enumeration e;
         elementName=sTagName;
    requestName=sAttrName;
    File f = new File(sFileName);
    // Use an instance of ourselves as the SAX event handler
    DefaultHandler handler = new ReadXmlSax();
    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
    // Parse the input
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse(f, handler);
    } catch (Throwable t) {
    t.printStackTrace();
    e = v.elements();
    return(e);
    //===========================================================
    // SAX DocumentHandler methods
    //===========================================================
    public void startDocument()
    throws SAXException
    public void endDocument()
    throws SAXException
    public void startElement(String namespaceURI,
    String sName, // simple name
    String qName, // qualified name
    Attributes attrs)
    throws SAXException
              //System.out.println(elementName);
              if (qName.equals(elementName))
                   String serverName = attrs.getValue("",requestName);
                   v.addElement(serverName);
    }

    I attached the main call the ReadXmlSax class. I added the
    "system.out.println(elementName);" in the function getAttribute and startElement as well. I got printing out "name" for elementName from function getAttribute but got others printing out "null" for elementName from function startElement. Any suggestions? thanks
    import java.io.*;
    import java.util.*;
    import ReadXmlSax;
    public class ReadElement
         public static void main(String argv[])
              ReadXmlSax r = new ReadXmlSax();
              Enumeration e = r.getAttribute("dre.xml","server","name");
              try{
                   while (e.hasMoreElements()) {
                   System.out.println((String)e.nextElement());}
              }catch(Throwable t){
                   t.printStackTrace();
    <strong>test</strong>

  • How can I pass an object to an inner method?

    Hi all,
    I'm stuck with a tiny problem here, hope someone can help out:
    I receive an UndoableEditEvent object in my method and I then want to apply that object to a JTextArea, my understanding is that I need to add a listener to the JTextArea.. but it won't see my UndoableEditEvent object.
          public static void edit( UndoableEditEvent e ) {
                final UndoManager undo = new UndoManager();
                Document doc = text_in.getDocument();
                doc.addUndoableEditListener(new UndoableEditListener() {
                public void undoableEditHappened(UndoableEditEvent e) {
                    System.out.println(e.getEdit());
                     undo.addEdit(e.getEdit());
    Any ideas?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Well, that looks like the right code for adding a listener to your JTextArea... except for the bit where the code is inside a static method that has an UndoableEditEvent as a parameter. Just get rid of that, and put the inside code immediately after the line of code where you create your JTextArea. You will probably have to make your UndoManager an instance variable of your class, too.

  • How can I pass objects across neywork?

    How can I pass a ObjectOutputStream to a ObjectInputStream, across a socket?
    Thanks in advance for your posts!

    Or maybe I am misunderstanding your question?-Probably
    Lets see: ObjectOutputStream passes data trought aout
    Stream; ObjectInputStream receives data trought a in
    Stream: so, I suppose that they can use as streamsthe
    connections betwen two sockets, in one point the
    ObjectOutputStream sending, an in another the
    ObjectInputStream receiving.Yes. The sockets provide the connections, and you can
    call getInputStream or getOutputStream on the sockets
    to read what the other guy is sending, or to write to
    the other guy. You don't actually pass the sockets or
    streams back and forth--they're just the channels by
    which you pass your data.I knew that, thanks anyway. But my question is how can I pass objects throught that streams.
    Anyone knows?
    Thanks

  • How can I pass arguments from one MIDlet to another MIDlet

    Hi everybody !
    Can anybody help me in knowing that how can I pass the parameters from one
    MIDlets to another one in same application.
    I am devloping a application in which I am using more than two MIDlet and I
    want to transfer Parameter from one MIDlet to another one.
    I just explain what I have done....
    I made a MIDlet "A" and "B" in the same project using NetBeans IDE.
    In MIDlet "A" I create the Object of MIDlet "B" so that the constructor of
    MIDlet "B" is called and parameter can be transferred.
    But when I run the program it shows me two MIDlet on the screen, that I
    doesn't need.
    Suggestion are most welcome....
    Thanks in advance
    Regards
    Bhagwat

    If you create two MIDlet in a midlet suite, it will display as you mentioned means you can't change the display style.

  • How can I pass a xml file to the webservice?

    Hello friends,
    How can I pass the XML file to any webservice API ?
    I have all the inputs of API in to the XML file.
    Please note:- I don't intend to do any .NET or Java coding to populate the data in the objects .Instead I plan to input the data to the webservice direcly from the XML file required schema.
    If necessary I can use Oracle Bpel process manager for it.
    Thanks and regards
    Ram Krishna Tripathi
    [email protected]

    Well, I've used it (or rather: tried it); did not/could not find the many options to export at a nearly lossless conversion for HD footage (hence my disclaimer "don't know"). Here is a screenshot of the Handbrake options:
    And here are the choices and settings from MPEG Streamclip:
    Maybe not empirical, but enough for me to have an opinion.

  • How can i pass token parameters

    Dear all
    i have wrote this code for side tab bar
    OAStaticStyledTextBean bulletTextOne =
    (OAStaticStyledTextBean)createWebBean(pageContext, STATIC_STYLED_TEXT_BEAN, null, "textOne");
    bulletTextOne.setText(pageContext, yahooText);
    bulletTextOne.setCSSClass("OraLinkText");
    bulletTextOne.setDestination(yahooUrl);
    bulletList.addIndexedChild(bulletTextOne);
    String x="OA.jsp?page=/crm/oracle/apps/xxcrm/crmmgmt/quotationmgmt/webui/xxcrmquotationsearchPG";
    OAStaticStyledTextBean bulletTextOne =
    (OAStaticStyledTextBean)createWebBean(pageContext, STATIC_STYLED_TEXT_BEAN, null, "textOne");
    bulletTextOne.setText(pageContext, yahooText);
    bulletTextOne.setCSSClass("OraLinkText");
    //bulletTextOne.setDestination(yahooUrl);
    bulletTextOne.setDestination(x);
    bulletList.addIndexedChild(bulletTextOne);
    Here i am navigating from one page to another page when i click on link
    her at that same time how can i pass token parameter to this link
    like ${oa.xxcrmCostsheetVO1.OpcsOpportunityid}
    Regards
    Sreekanth

    Hi,
    First grab the value of OpcsOpportunityid from View Object and store it in variable
    say
    String id = (String)row.getAttribute("OpcsOpportunityid").toString();
    You can pass parameters like
    String x="OA.jsp?page=/crm/oracle/apps/xxcrm/crmmgmt/quotationmgmt/webui/xxcrmquotationsearchPG&param1="+id;
    and then set the destination of link
    bulletTextOne.setDestination(x);
    Thanks,
    Gaurav

  • How can I pass field value betwen view in ICWC?

    Hi experts,
    I am new to this BSP programming. I have some requirements to modify standard ICWC in CRM 5.0
    Hope can get some advices and helps here.
    I have added a new field called <status> to context note SEARCHCUSTOMER in BupaSearchB2B view and also the same field name to context note CUSTOMER in BupaCreate view.
    I have added the field into both the HTM views and able to execute thru WebClient. However, I have one problem in passing the <status> value from BupaSearchB2B view  to the BupaCreate view when I click on the 'create' button.
    I do search and saw this thread How can I pass field value beetwen view in IC Web Client? , but i cant figure out how it works.
    Do I need to create the field <status> to context note CUSTOMER in BupaSearchB2B? Currently the context note does not have any attributes.
    Really appreciate for any help.
    Edited by: mervyn tay on Apr 7, 2009 11:42 AM

    solved by myself...
    code in the CREATE_ACCOUNT method.
            ev_entity->set_property( iv_attr_name = 'ZZICNO'
                                     iv_value = lv_icnum1 ).

  • How can I pass an empty array to a parameter of type PLSQLAssociativeArray

    How can I pass an empty array to a parameter of type PLSQLAssociativeArray in VB? I defined the parameter like this
    Dim myArray() as String = new String() {}
    Dim myPara as new Oracle.DataAccess.Client.OracleCollectionType.PLSQLAssociativeArray
    myPara = 0
    myPara.Value = myArray
    When I execute my stored procedure giving the above parameter, I got error saying OracleParameter.Value is invalid.
    I have tried to give it the DBNull.Value, but it doesn't work either.
    Note: everything works fine as long as myArray has some item in there. I just wonder how I can make it works in case I have nothing.
    Thank you,

    How can I pass an empty array to a parameter of type PLSQLAssociativeArray in VB? I defined the parameter like this
    Dim myArray() as String = new String() {}
    Dim myPara as new Oracle.DataAccess.Client.OracleCollectionType.PLSQLAssociativeArray
    myPara = 0
    myPara.Value = myArray
    When I execute my stored procedure giving the above parameter, I got error saying OracleParameter.Value is invalid.
    I have tried to give it the DBNull.Value, but it doesn't work either.
    Note: everything works fine as long as myArray has some item in there. I just wonder how I can make it works in case I have nothing.
    Thank you,

  • How can i pass the Input value to the sql file in the korn shell ??

    Hi,
    How can i pass the Input value to the sql file in the korn shell ??
    I have to pass the 4 different values to the sql file and each time i pass the value it has to generate the txt file for that value like wise it has to generate the 4 files at each run.
    can any one help me out.
    Raja

    Can you please more elaberate., perhaps you should more elaberate.
    sqlplus is a program. you start it from the korn shell. when it's finished, processing control returns to the korn shell. the korn shell and sqlplus do not communicate back and forth.
    so "spool the output from .sql file to some txt file from k shell, while passing the input parameters to the sql file from korn shell" makes no sense.

  • How can I pass more than one parameters in PDK-URL services?

    Hi all,
    How can I pass more than one parameters in PDK-URL service? All samples on Portal Center shows just one parameter passing.
    <inputParameter class="oracle.portal.provider.v1.URLPortletParameter">
    <name>csz</name>
    <isMandatory>false</isMandatory>
    <displayName>What location do you want a map for (City, State or Zip)?</displayName>
    </inputParameter>
    How can I write the privider.xml file for passing multiple parameters?

    I answer to my question. I've got the answer.
    I repeatly write down the <inputParameter> tags, and it works.

  • How can i pass more than 1 param to servlet to show blob image

    Hi
    my servlet expects 2 param to SELECt an image from a blob column
    public class ImageBlobServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    IOException {
    response.setContentType(CONTENT_TYPE);
    String ImageId = request.getParameter("id");
    String TipImg = request.getParameter("tip");
    OutputStream os = response.getOutputStream();
    Connection conn = null;
    try {
    Context ctx;
    ctx = new InitialContext();
    DataSource ds = (DataSource)ctx.lookup("java:/comp/env/jdbc/rhDS");
    conn = ds.getConnection();
    PreparedStatement statement = conn.prepareStatement("select FIT from " +
    "RHH_FOTOS IMG " +
    "where IMG.IDASSO = ? and IMG.TIM_COA = ?");
    statement.setInt(1, new Integer(ImageId));
    statement.setString(2, TipImg);
    To display the image i tried to use:
    <af:image id="ot1"
    *source="/imageblobservlet?id=#{bindings.Con.inputValue}?tip=#{"EMP"}"*
    shortDesc="Foto"/>
    but i receive all content in the get of first param.
    String ImageId = request.getParameter("id");
    How can i pass one more then 1 param in EL.
    Thanks in advance

    Hello,
    seems to me you're using wrong separator for the second param into your URL:
    <af:image id="ot1" source="/imageblobservlet?id=#{bindings.Con.inputValue}
    tip=#{"EMP"}" shortDesc="Foto"/>
    I think it should be:
    <af:image id="ot1" source="/imageblobservlet?id=#{bindings.Con.inputValue}
    tip=#{"EMP"}" shortDesc="Foto"/>
    Jack

  • How can I pass parameters from one process flow to another process flow?

    How can I pass parameters from one process flow to another process flow (sub process) in warehouse builder? let me know the steps I have to do in warehouse builder.
    Thanks in advance,
    Kishan

    Hi Kishan,
    Please post this question to the Warehouse Builder forum:
    Warehouse Builder
    Thanks, Mark

  • How can I pass data generated in a SubVI inside a Case Structure out of the Case Structure?

    Hello,
    I am using a USB 2701 to control a heater.  I have three SubVIs that are all working properly on their own.  I'd like to use an Enum to select which of the SubVIs is running at a given time.  The problem is that no data is passing out of the case structure.  How can I pass the temperatures and heater outputs acquired by the SubVIs to the main VI?  I've attached my some of my code below.  I can't attach more than 3 files, but you can see how the main VI is configured.  Like I said, the SubVIs are working individually, so you shouldn't really need to look at them.
    Thank you,
    CJones581
    Attachments:
    RampHeater6-21-07.vi ‏305 KB
    69_Heater_Case.vi ‏23 KB
    HeaterTCD6-21-07.vi ‏210 KB

    CJones,
    You might check a couple of things.
    Your HeaterTCD... VI has a While loop with a stop button condition.  HeaterTCD pass out values only when it finishes running.  If it doesn't pop open the front panel (which usually doesn't happen when running a SubVI) you could run into a stuck loop because you don't have access to the Stop button.  This could appear in the form of no data being passed out (because the SubVI never stops running).  The primary VI opens the HeaterTCD VI, starts it, and waits for the VI to finish and pass final values .
    Secondary note: Unless you want your SubVI panel (which probably isn't open when running the main VI) to update continuously, consider moving your Temperature Graph and Temperature oC indicators outside the while loop.  Pass final values to them via a tunnel, since the main VI will only read their values after the loop finishes running, anyway.
    It might help to add error management to HeaterTCD like you have for RampHeater.  If you connect error lines with Error Outs to your main VI, that will help tell if there is an error somewhere that is preventing info output.
    RampHeater SubVI has the same issue with the stop button.  It is also probably getting stuck in the While loop waiting for a manual push of that SubVI's Stop button.
    An easy way to test this would be to set up a logic circuit so that when the While loop iteration counter reaches a certain number, it registers True and sends it to the conditional.  I know this isn't what you want to do long-term, but if that lets your SubVI return outputs it means that the SubVI was just never stopping.
    Hope that helps.
    David C, Applications Engineering
    David C
    Applications Engineering

  • HT201250 how can i pass information from one mac to another mac by using the time capsule

    how can i pass information from one mac to another mac by using the time capsule

    If you want to transfer files, settings, etc., you must open Migration Assistant (Applications > Utilities) in the Mac that you want to transfer the files and follow the instructions

Maybe you are looking for

  • PDFs will not open in IE V8

    I'm using IE Version 8 and when I try to open PDFs in my browser, it hangs...then eventually gives me an error saying "There is a problem With Adobe / Acrobat Reader.  Please exit Adobe Acrobat / Reader and Try again." An example are the PDF download

  • Weblogic 10.3TP, JAX-WS and Spring integration

    Hi all We are using JAX-WS and Spring (2.0.6) and our target platform will be Weblogic 10.3. We would like to benefit from Spring injection in our web service classes. However I cannot get it to work. I follow the instructions described here: [url ht

  • List of Open SQL Function

    Can anybody provide me a list of all the Open SQL Functions? I know some of it like Minimum,Maximum,etc. but I'm looking for a complete list of it.

  • Multiple columns in operator

    When I submit a query like this: select * from tab1 where (column1, column2) in ((va111, val21),(val12, val22),(val13,val23)....) It only returns the records matches column1=val11 and column2=val21. How to change this query to get all values?

  • Folder and Question Mark

    I asked this question earlier but the problem keeps reoccuring. Every morning my iMac is flashing a folder and question mark. I just push the button in the back to turn it off, turn it right back up and it runs perfect all day. But the next morning i