Skip to content

Commit 1545ae4

Browse files
committed
Applying Brian Egge's patch to CLI-21 that resurrects the clone() method
git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/cli/branches/cli-1.0.x@547721 13f79535-47bb-0310-9956-ffa450edef68
1 parent a52a9af commit 1545ae4

2 files changed

Lines changed: 45 additions & 2 deletions

File tree

src/java/org/apache/commons/cli/Option.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
3434
* @version $Revision$
3535
*/
36-
public class Option {
36+
public class Option implements Cloneable {
3737

3838
/** constant that specifies the number of argument values has
3939
not been specified */
@@ -632,6 +632,12 @@ public int hashCode()
632632
return result;
633633
}
634634

635+
protected Object clone() throws CloneNotSupportedException {
636+
Option option = (Option) super.clone();
637+
option.values = new ArrayList(values);
638+
return option;
639+
}
640+
635641
/**
636642
* <p>Clear the Option values. After a
637643
* parse is complete, these are left with data in them

src/test/org/apache/commons/cli/OptionTest.java

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,42 @@ public void testClear() {
3131
option.clearValues();
3232
assertEquals(0, option.getValuesList().size());
3333
}
34-
34+
35+
// See http://issues.apache.org/jira/browse/CLI-21
36+
public void testClone() throws CloneNotSupportedException {
37+
Option a = new Option("a", true, "");
38+
Option b = (Option) a.clone();
39+
assertEquals(a, b);
40+
assertNotSame(a, b);
41+
a.setDescription("a");
42+
assertEquals("", b.getDescription());
43+
b.setArgs(2);
44+
b.addValue("b1");
45+
b.addValue("b2");
46+
assertEquals(1, a.getArgs());
47+
assertEquals(0, a.getValuesList().size());
48+
assertEquals(2, b.getValues().length);
49+
}
50+
51+
private static class DefaultOption extends Option {
52+
53+
private final String defaultValue;
54+
55+
public DefaultOption(String opt, String description, String defaultValue) throws IllegalArgumentException {
56+
super(opt, true, description);
57+
this.defaultValue = defaultValue;
58+
}
59+
60+
public String getValue() {
61+
return super.getValue() != null ? super.getValue() : defaultValue;
62+
}
63+
}
64+
65+
public void testSubclass() throws CloneNotSupportedException {
66+
Option option = new DefaultOption("f", "file", "myfile.txt");
67+
Option clone = (Option) option.clone();
68+
assertEquals("myfile.txt", clone.getValue());
69+
assertEquals(DefaultOption.class, clone.getClass());
70+
}
71+
3572
}

0 commit comments

Comments
 (0)