Menu

#1 Generated clone() does not handle Dates correctly

open
nobody
None
5
2003-12-05
2003-12-05
Anonymous
No

Here is a source file with a generated clone() method
using CodeSugar

package test;
import java.util.Date;

public class Test
{
private Date testDate = new Date();
private String testString = new String();

public Object clone()
{
Test inst = new Test();
inst.testDate = this.testDate == null ? null : (Date)
inst.testDate.clone();
inst.testString = this.testString == null ? null : new
String(this.testString);
return inst;
}
}

The string is done correctly by creating a new string
from the current object's string.
The date is done incorrectly by cloning the date from
the wrong object. It clones the date on the newly
created inst object and assigns it back to the inst
object.

The line should read
inst.testDate = this.testDate == null ? null : (Date)
this.testDate.clone();

or

inst.testDate = this.testDate == null ? null : new Date
(this.testDate.getTime());

Discussion

  • Rafael Ubiratam Clemente Afonso

    Logged In: YES
    user_id=825871

    I have same problem. :(

     
  • Rafael Ubiratam Clemente Afonso

    Logged In: YES
    user_id=825871

    I read code from CloneGenerator And I see where is the
    problem. In String cloneObject(String a, String type) method
    we have:

    protected static String cloneObject(String a, String type) {
    String c;
    if ("String".equals(type) ||
    "java.lang.String".equals(type)) {
    c = "new String(this." + a + ")";
    }
    else if ("Integer".equals(type) ||
    "java.lang.Integer".equals(type)) {
    c = "new Integer(this." + a + ".intValue())";
    }
    else if ("Long".equals(type) ||
    "java.lang.Long".equals(type)) {
    c = "new Long(this." + a + ".longValue())";
    }
    else if ("Float".equals(type) ||
    "java.lang.Float".equals(type)) {
    c = "new Float(this." + a + ".floatValue())";
    }
    else if ("Double".equals(type) ||
    "java.lang.Double".equals(type)) {
    c = "new Double(this." + a + ".doubleValue())";
    }
    else if ("Boolean".equals(type) ||
    "java.lang.Boolean".equals(type)) {
    c = "new Boolean(this." + a + ".booleanValue())";
    }
    else {
    c = "(" + type + ")inst." + a + ".clone()";
    }

    return "inst." + a + " = this." + a + " == null ?
    null : " + c + ";";
    }

    Problem is in "else" condition. Intead wirte:
    c = "(" + type + ")inst." + a + ".clone()";
    Correct would be:
    c = "(" + type + ")this." + a + ".clone()";

     
  • Nobody/Anonymous

    Logged In: NO

    The same is true for BigDecimals

     
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.