Clone Objects

Hi everybody,
I have the next trouble, I need to clone an Object, but the method "clone()" in the Object class is protected.
I am working with a DBMSOO that provide me the following classes: Database, Transaction. I want to have a generic command that retrieve Objects from a database Object-Oriented, and then to make a cast to a specific class.
This is the code:
public class Lookup
private Object object;
public Lookup
Database db = new Database();
db.open( "dbUrl->server", Database.OPEN_READ_ONLY );
Transaction txn = new Transaction( db );
txn.begin();
object = db.lookup( "idObject" );
txn.commit();
db.close();
public Object getObject() {
return object;
My trouble is that when the Transaction is finished with commit() method, the object reference is null. I thought to clone the Object, but is not posible.
Could anyone help me, please?
Sincerely,
Alvaro
PS: Sorry, for my english. I know it isn't very good.

Hi DrClap,
I understand you, but if I don't write the sentence:
txn.commit()
that close the Transaction, the reference "object" isn't null.
What's the matter?
Thanks a lot for your interesting.
Alvaro

Similar Messages

  • How To Clone Objects?

    Hi folks,
    I'd like to know, if there is a way to clone any object in ABAP? Using implemented interface method if_os_clone~clone is nice, but doesn't help me, because it works only for classes that have implemented corresponding interface. For example it doesn't help me to clone objects of class 'TYPE REF TO DATA'.

    You're right, 'TYPE REF TO DATA' isn't a class. Forget this point!
    DATA:
      object1 TYPE REF TO YCLASS,
      object2 TYPE REF TO YCLASS.
    CREATE OBJECT object1.
    object2 = object1.
    In this example object1 and object2 reference to the same instance. But I want to create a copy of object1, so that there are two separate instances of class YCLASS.

  • It seems you cannot clone objects with attributes using lazy loading in JPA

    I have an entity with an attribute using lazy loading:
    @Entity
    public class B {
    @ManyToOne(fetch=FetchType.LAZY)
    private A a;
    @Entity
    public class A {
    Assume the following code:
    A a1 = new A();
    A a2 = new A();
    B b1 = EntityManager.find(B.class, ...);
    b1.setA(a1);
    B b2 = b1.clone();
    b2.setA(a2);
    Now with lazy loading enabled I get b1.getA() == a2 instead of b1.getA() == a1. Moreover, the debugger displays the same value holder in b1 and b2 for the attribute a. It appears as if cloning does not make a (deep) copy of the value holder managing the attribute a.
    How can I create a copy b2 of b1, such that the value holder managing a in b1 is a different object as the value holder managing a in b2?
    Thanks, Thomas.

    I have filed a bug to have this addressed in Oracle TopLink 11gR1. I would recommend you file a bug against TopLink Essentials in GlassFish or if you have a support contract report the issue to metalink to have the issue resolved.
    If this is urgent I did try fixing the issue with a small helper method using some reflection. This method is simplified through its throwing of Exception. If you wish to use something like this I would recommend proper error handling.
         * Helper method for cloning an entity and fixing the woven value-holders to
         * complete a proper shallow cloning.
        public static Employee clone(Employee entity) throws Exception {
           Employee clone = entity.clone();
           // Now fix the cloned ValueHolder references
           Field[] fields = entity.getClass().getDeclaredFields();
           for (int index = 0; index < fields.length; index++) {
               Field field = fields[index];
               if (field.getName().startsWith("_toplink_")) {
                   field.setAccessible(true);
                   ValueHolderInterface vhi = (ValueHolderInterface)field.get(entity);
                   Object value = vhi.isInstantiated() ? vhi.getValue() : null;
                   field.set(clone, new ValueHolder(value));
           return clone;
        }Doug

  • Clone object

    Hi,
    I have a question concerning After Effects CS4, how can i dublicate (not clone) an object so that they don't share their parameters. When i change parameter in copy i want it only there, without changing the orginal object. I tried to copy and dublicate layers non of them worked.
    Thanks,
    MK

    Duplicate your items in the project window, not the timeline.
    Mylenium

  • When do we override our own clone method not the Object class clone method

    Hi,
    I have a confusion in overriding clone method.We can create clone object by writing Object.clone() but some times I have seen writing our own clone method ,when do we write this,also clone() is defined protected and when we write our own clone it is said to write it public,why?
    Thanks
    Sumit

    protected methods can only be called in the same class and it subclass. You can make clone protected if this is all you need.
    However if you need to clone() the object from another class, it need to be public.
    This is the same for any method.
    Also as Object.clone() is protected you cannot make it private or package-local (this is true of any protected method)

  • Is this write way to clone a object?

    All,
    I this the correct way to clone a object? if not so can anyone point me the right way to do that. Because this method is taking longer time to execute.
    import java.io.*;
    public class ObjectCloner
        public ObjectCloner()
        public static Object clone(Object obj)
            throws Exception
            ByteArrayOutputStream bstream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bstream);
            out.writeObject(obj);
            out.close();
            ByteArrayInputStream binstream = new ByteArrayInputStream(bstream.toByteArray());
            ObjectInputStream oin = new ObjectInputStream(binstream);
            Object newobj = oin.readObject();
            return newobj;
        public static int sizeOf(Object obj)
            try
                ByteArrayOutputStream bstream = new ByteArrayOutputStream();
                ObjectOutputStream out = new ObjectOutputStream(bstream);
                out.writeObject(obj);
                out.close();
                return bstream.toByteArray().length;
            catch(Exception ex)
                ex.printStackTrace();
            return 0;
    }

    calvino_ind wrote:
    i might be wrong, but i think there are some really easier ways to clone an object:
    public class Age {
    int numberOfYears;
    public Age(int numberOfYears) {
    this.numberOfYears = numebrOfYears;
    public Object clone() {
    return new Age(this.numberOfYears);
    No! This is very wrong. For this simple example, all one needs is class Age to implement Cloneable and
    public Object clone() {
             return super.clone();
    }which will automatically give you a shallow clone of the the class.
    Consider what ill happen with your approach when one clones superclasses of class Age.
    Edited by: sabre150 on May 26, 2008 3:42 PM

  • Difference between "clone" and creating a new object

    Hi experts,
    What on earth is the difference between:
    1)creating a new object by using the "clone()" method and
    2) just creating a new object?
    Let me be a bit more specific:
    if there's a class called "Book" and suppose we've already created an object called "japaneseBook", any difference between "Book spanishBook = new Book();" and "Book spanishbook = japaneseBook.clone()"?
    Thank you.
    Eileen

    The purpose is very obvious. At anytime in the running application, when Objects have been changed, and you desire to make another one of the same kind, you can't use new. You would use clone. The newer Object would have the same values in the variables. Now i got a question.. an important issue.
    public class XYZ{   
      public static int t = 10;
    } // default constructor is present by default.
                     //In another portion i have the following..
    private XYZ x = new XYZ( );  // private Object!!
         // Now what about this one????
    public XYZ x1 = x.clone( );  // public !!, well
    What impact of this code can be there to break the rules of good OOP design??? Is it that a clone Object would have the same access of itself (not of its variables) or different one?????????

  • Always override: toString(), clone(), equals(Object obj)?

    In classes that I write Is there any reason to not always override:
    public String toString();
    public boolean equals();
    public Object clone(Object obj);Further, why not always provide a default Comparator ?
    public Comparator getDefaultComparator();This seems logical?

    kakusaretasuna wrote:
    thank you.
    I am just beginning to learn Java, and so I am making a checklist of things to do when I write a class.
    When it makes sense, I will always implement:
    toString()
    clone()
    equals()
    getDefaultComparator()getDefaultComparator? No, I wouldn't do that. Where did you get that idea from?
    And if you override equals, you should always override hashCode as well, and vice versa.
    As a rule, I do not override those methods unless I have a specific reason to.
    And, I learned that by default a Java class is not Serializable . Therefore, for each of my
    classes, I need to adjust them to safely be Serializable , and then declare them Serializable Only if there's a reason to serialize them. Again, it doesn't make sense for all classes, or even most.
    This makes sense to me, however, I don't want to appear foolish to exeperienced developers. For example, I learned that:Worry less about appearing foolish and more about learning. Everybody had to start somewhere, and this stuff is generally not intuitive. Nobody cares if you don't automatically know it all.
    >
    private final void foo(); // "final" is annoying and foolish?As with most things, there are at least two schools of thought on that. In general, I don't make methods final unless I specifically don't want them overridden. Some people feel you should declare them final by default, and only remove the final in cases where there are specific reasons to override them. Neither is right or wrong. It's mostly a matter of convention, and somewhat a matter of context.
    private void foo() { this.privateMethod(); } // "this" is annoying and foolish?I personally hate using "this" when it's not necessary, and it's never necessary in the case of method calls. It doesn't even add any clarity. It's just clutter.
    >
    I am sure there are many other construts that experienced developers avoid.Yes, but don't worry about learning them all right now.

  • Using a registered object outside a UnitOfWork

    We are constructing a multi-tiered application using TopLink 4.6. The Model and Controller are in different JARs but are part of the same EAR. Data objects mapped in TopLink are sent by the Model to the Controller. The Controller may modify these objects locally, and send them back to the Model for persisting.
    When the Controller makes a request for a data object to the Model, the Model does the following -
    1. Gets the object from the TopLink cache through a query
    2. Gets a UnitOfWork
    3. Registers the object with the UnitOfWork to get the clone
    4. Releases the UnitOfWork
    5. Returns the clone to the Controller
    I am registering the object with a UnitOfWork, even though I am not modifying it in that UnitOfWork.
    I have to do this because the object model is very complicated. The Controller needs access to the root object, and also all of its nested parts. Using this technique, I retain the benefit of Indirection. The other option is to use a ObjectCopyingPolicy, but that is expensive as the Model is forced to do a cascadeAll copy. Also, I cannot send back the original object returned by the query because this object comes from the cache, and the Controller could end up modifying it, thus causing possible data inconsistency.
    After the Controller sends back the modified object, the Model now does the following -
    1. Check the incoming object and perform business validations
    2. Get a UnitOfWork
    3. Do a deepMergeClone on the UnitOfWork to save the object.
    4. Commit or release the UnitOfWork
    This seems to work without any problems. Will this have any other repercussions? The object is initially obtained through a different UnitOfWork, and is saved using a different UnitOfWork.
    Is there a better way of handling this situation?
    Thanks

    Hi,
    The key here is that the object is cloned (copied) and the clone (copy) is returned to the client.
    The client then makes the changes to the copy (the original is still in the session cache and has not changed)
    When the object is register, TopLink does a look-up, using the copy Object, in the session to find the original object, it then makes a clone of the original object.
    You now have three copies of the same object. The Original Object (no changes), the clone of the Original Object (no changes yet), and the copy Object (with client changes).
    The next step merges the Original Object Clone (without changes) and the copy Object Clone (with changes).
    Now your system has two copies, The Original Object (no changes) and the clone Object (with changes).
    Now on commit, TopLink compares the Original with the Clone and updates the DB.
    Raanan.

  • How can i copy,paste an Object ?

    How can i copy,paste an Object which i define by myself?

    implements Cloneable and define a clone method, for example
    public class ObjectA  implements Cloneable {
       // Data member
       String data;
       public ObjectA() {
       public void setData(String data) {
          this.data = data;
       public Object clone() {
           ObjectA tempObject = new ObjectA();
           tempObject.setData(this.data);
           return tempObject;
    }

  • Reference Objects and Pooling

    I am trying to create a Pool class that does not require the caller to explictly return the objects. I thought I might be able to use Phantomreference or WeakReference to detect when the user no longer had reference to the object and thus reclaim it and put it back in the pool. The issues with these are this:
    1) WeakReference is cleared (clear()) before it is added to the ReferenceQueue not to mention the object is finalised before as well.
    2) PhantomReference is not cleared but it is finalized. Not that it matters because you can never access the referant.
    So what I did is subclass PhantomReference and created an Interface called Proxy. The subclass would take a proxy referant containing the actual reclaimable object and it would store the relaimable object as a hard referant and the proxy to that as the Phantom referant. Thus when the client was no longer using the proxy the erference would be added to the reference queue and I could get the actual reclaimable object as opposed to the proxy via a call to get().
    The problem with this approach has been that not all classes lend well to being proxied. The idea situation would be that the Proxy would extend the actual class thus CASTING would work as normal.
    public StringBufferProxy extends StringBuffer implements Proxy {
    private StringBuffer proxy;
    public StringBufferProxy(StringBuffer proxy)
    this.proxy = proxy;
    public Object getProxied()
    return proxy;
    public void anyMethod()
    proxy.anyMethod();
    The obvious problem with the above is that StringBuffer is final and thus can't be extended. Similar problems with Thread as it relates to its final methods. So in the end after going around in circles for awhile I realized this concept would only really be practicle for Interface based classes.
    Has anyone else worked this problem and solved it?
    }

    all cases the referant has allready been finalized. In...
    So what I tried to do was create a proxy class that
    wraps the actual pooled item....
    This has numerous problems.You may like my method. Someone needs to tell me if this is a ``bad thing'' but I've used it quite successfully. I wrote a cache class a little while ago (very similar to your Pool needs). It's a cloning cache. Let me simplify a VERY complex cache:
    class Clone implements Cloneable {
        private Object o;
        Clone(Object o) {
            super();
            this.o = o;
        public Object getObject() { return o; }
        public Clone getClone() throws ... {
            return (Clone)super.clone();
    } // CloneThis sets up the clone, now:
    class CloneReference extends WeakReference implements Comparable { // or extend any Reference that makes sense to you
        private Clone clone = null;
        CloneReference(Clone referent, ReferenceQueue q) throws ... {
            super(referent,q);
            try {  // don't really have to try, but...
                clone = (Clone)referent.getClone();
            } catch(Exception dowhatever) { ... }
        public Object getObject() {
            Object ret = null;
            if(clone!=null) ret = clone.getObject();
            return ret;
        // now implement Comparable
    } // CloneReferenceNow in your Pool maintain your ReferenceQueue, when you add a new Object into it, purgue this queue. In my cache I have a CacheEvent/CacheListener that is event fired during the purging of this queue. More later. When adding a new object into your Pool, add a reference to a new CloneReference object:
    private ReferenceQueue q;  // init elsewhere
    public void add(Object o) throws ... {
        CloneReference cr = new CloneReference(
              new Clone(obj)
            , q
        // now add this cr, not the o
    }When purging the queue, poll() your ReferenceQueue and then obtain the CloneReference. Get your object back out (this will not be null or yet finalized) using CloneReference.getObject(), then fire off your interpretation of my CacheEvent to your version of my CacheListener.
    Note that the ReferenceQueue maintains a reference to the original Clone, but the Reference itself has a clone of that Clone which we will NOT be GCd or nullified still maintaining a reference to the original object.
    If you need further help I can probably provide a truncated source of a simple Cache.

  • Trouble cloning object. Doesn't seem to be cloneable, why?

    Hello!
    I have this function in my class which is called "clone" (overrides clone). But i don't seem to be able to return a copy of my class object. Why is that?
    Here is my class (check the clone method):
    import java.lang.Object;
    import java.io.*;
    import java.util.*;
    public class RatNum {
        int numerator; // = täljare
        int denominator; // = nämnare
        RatNum()
            numerator = 0;
            denominator = 1;
        RatNum(int a)
            set(a);
        RatNum(int a, int b)
            set(a, b);
        RatNum(RatNum r)
            set(r);
        public void set(int a, int b)
            if(b == 0)
                throw new NumberFormatException("Denominator = 0");
            else
                boolean isNegative = false;
                if(a < 0 && b < 0)
                    a = a-(a*2);
                    b = b-(b*2);
                else if(a < 0) //r.set(-49, 168);
                    a =  a-(a*2);
                    isNegative = true;
                else if(b < 0) //r.set(49, -168);
                    b = b-(b*2);
                    isNegative = true;
                int divide = sgd(a, b);
                a = a/divide;
                b = b/divide;
                if(!isNegative)
                    numerator = a;
                else
                    numerator = a-2*a;
                denominator = b;
        public void set(int a)
            numerator = a;
            denominator = 1;
        public void set(RatNum r)
            numerator = r.getNumerator();
            denominator = r.getDenominator();
        public int getNumerator()
            return numerator;
        public int getDenominator()
            return denominator;
        @Override
        public String toString()
            String fracture;
            fracture = numerator+"/"+denominator;
            return fracture;
        public static RatNum parse(String s)
            RatNum r = new RatNum();
            if(s.matches("[-+]?[0-9]+"))
                r.set(Integer.parseInt(s), 1);
            else if (s.matches("[-+]?[0-9]+[/][-+]?[0-9]+"))
                String[] n = s.split("/");
                r.set(Integer.parseInt(n[0]), Integer.parseInt(n[1]));
            else
                throw new NumberFormatException("strängen är felformaterad");
            return r;
        @Override
        public Object clone()
            Object a = null;
            try
                a = super.clone();
            catch (CloneNotSupportedException e)
               System.out.println("Not supported!");
            return a;
        public boolean equals(RatNum r)
            boolean isSame = false;
            if(r.denominator == this.denominator && r.numerator == this.numerator)
                isSame = true;
            return isSame;
        public boolean lessThan(RatNum r) //demo = nämnare
            boolean isLess = false;
            int compare = r.denominator * this.numerator;
            int original = this.denominator * r.numerator;
            if(compare < original)
                isLess = true;
            return isLess;
        public RatNum add(RatNum r)
            RatNum newRat = calculate(r, '+');
            return newRat;
        public RatNum sub(RatNum r)
            RatNum newRat = calculate(r, '-');
            return newRat;
        public RatNum mul(RatNum r)
            RatNum newRat = calculate(r, '*');
            return newRat;
        public RatNum div(RatNum r)
            RatNum newRat = calculate(r, '/');
            return newRat;
        public RatNum calculate(RatNum r, char operator)
            RatNum newRat = new RatNum();
            switch(operator)
                case '+': newRat.set((r.denominator*this.numerator)+(this.denominator*r.numerator), r.denominator*this.denominator); break;
                case '-': newRat.set((r.denominator*this.numerator)-(this.denominator*r.numerator), r.denominator*this.denominator); break;
                case '*': newRat.set((r.denominator*this.numerator)*(this.denominator*r.numerator), r.denominator*this.denominator); break;
                case '/': newRat.set((r.denominator*this.numerator)/(this.denominator*r.numerator), r.denominator*this.denominator); break;
                default: throw new NumberFormatException("operatorn är felformaterad");
            return newRat;
        public static int sgd(int a, int b)
            int rest=1;
            while (rest!=0)
                rest = a%b;
                a = b;
                b = rest;
            return a;
    }Thanks in advance!

    It doesn't implement Cloneable

  • Cineware Limitations (cloner w/ external compositing tag, camera morph tag)

    Hi!
    I've made the switch to AE CC 2014 and have been trying to use cineware instead of working with an AEC file. I have ran into some issues though. If I animate a camera in C4d using the Camera Morph Tag, The animation doesn't get extracted into AE with Cineware. This also happens if I add an external compositing tag to a cloner object. Both of these worked with the AEC file, but do not work with Cineware. Whats the deal?!

    The Camera Morph uses Python/ XPresso under the hood and needs to be baked. The external compositing tag is somehow borked. You can try to clone it to a Matrix Object with Nulls. This may work.
    Mylenium

  • Cloning an Object

    I've been trying to clone one of my custom objects for a few days now and tried all examples i could find. I also added "[RemoteClass]" before every class.
    I used a custom (which is probably the same) and the mx.utils.objectutils.copy function:
    public static function clone(value:Object):Object
        var buffer:ByteArray = new ByteArray();
        buffer.writeObject(value);
        buffer.position = 0;
        var result:Object = buffer.readObject();
        return result;
    Both gave me the same error message:
    "ArgumentError: Error #1063: Argument count mismatch on basecreatures.water::Naga(). Expected 1, got 0.
        at flash.utils::ByteArray/readObject() [....]"
    The class Naga is being extended by the class Creature, which both require some arguments. I used it like this:
    Game.player[ownerid].creaturelist.push(Game.clone(target));
    target is an object of the class Naga which is working perfectly. Using some other clone methods, the cloned object didn't get the functions of the Creature class.

    I don't believe you can clone objects that lack a zero-argument constructor. Can you make the argument optional?
    Maciek Sakrejda
    Truviso, Inc.
    www.truviso.com
    Truviso is hiring: http://www.truviso.com/company-careers.php?i=87

  • Saving changes to database

    HI
    I have a few queries running in my application.
    I want to be able to ask the user when he exists the program
    whether he wants to save changes.
    And I only want to ask this question if any changes have
    been made to any of the queries.
    Can someone tell me how can I do this?

    Hi,
    Yes u can do it in this way.Create a dataobj for the table.Override equals method and clone it before u start editing.and before u save the check for the equals of the clonned object with the original one.this is one of the way to do.
    Try it out..
    sreeni,
    [email protected]

Maybe you are looking for

  • Import issue from 10g to 11g

    Hi All, I have dump file from 10g having 1 table only, with blob column. I am trying to import it in a different user with different tablespace by keeping IGNORE=Y and i have created that table also having blob column but it gives following error: im

  • Need password dialogue box back.

    In iPhoto I'm locked out from sending photos in an email.  Only one opportunity to type in password correctly.  Anyone know how to get the password box back?  Thanks

  • Multiple parallel approval task

    Hi, Can anybody tell me how we can acheive multiple approval in OIM? I have a requirement where I have to send approval task to multiple approvers and based on each approvers response I have to AD group. Currently I have a request where a user can re

  • Query - unable to fulfill request for 65536 bytes of memory space

    Hi all,          When i executing query it is running for 20 mins and showing this below error. Please guide me on this. Error: - Unable to fulfill request for 65536 bytes of memory space - No more storage space available for extending an internal ta

  • HT204387 I would like to download my old contacts from my Samsung into my new iPhone 5C. How do I do it????????????

    I have tried using the bluetooth on the iPhone to search and pair with my ol samsung phone but it is rejecting the pairing? I would hate having to download the contact info manually. Is there a way to do this? Additionally how can I get teh iPhoen to