1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.sf.ezmorph.object;
18
19 import java.lang.reflect.Method;
20 import java.util.ArrayList;
21 import java.util.Iterator;
22 import java.util.List;
23
24 import net.sf.ezmorph.MorphException;
25 import net.sf.ezmorph.Morpher;
26
27 import org.apache.commons.lang.builder.HashCodeBuilder;
28
29
30
31
32
33
34 public final class ObjectListMorpher extends AbstractObjectMorpher
35 {
36 private Object defaultValue;
37 private Morpher morpher;
38 private Method morphMethod;
39
40
41
42
43
44
45
46
47
48 public ObjectListMorpher( Morpher morpher )
49 {
50 setMorpher( morpher );
51 }
52
53 public ObjectListMorpher( Morpher morpher, Object defaultValue )
54 {
55 super(true);
56 this.defaultValue = defaultValue;
57 setMorpher( morpher );
58 }
59
60 public boolean equals( Object obj )
61 {
62 if( this == obj ){
63 return true;
64 }
65 if( obj == null ){
66 return false;
67 }
68
69 if( !(obj instanceof ObjectListMorpher) ){
70 return false;
71 }
72
73 ObjectListMorpher other = (ObjectListMorpher) obj;
74 return morpher.equals( other.morpher );
75 }
76
77 public int hashCode()
78 {
79 return new HashCodeBuilder().append( morpher )
80 .toHashCode();
81 }
82
83 public Object morph( Object value )
84 {
85 if( value == null ){
86 return null;
87 }
88
89 if( !supports( value.getClass() ) ){
90 throw new MorphException( value.getClass() + " is not supported" );
91 }
92
93 List list = new ArrayList();
94 for( Iterator i = ((List) value).iterator(); i.hasNext(); ){
95 Object object = i.next();
96 if( object == null ){
97 if( isUseDefault() ){
98 list.add( defaultValue );
99 }else{
100 list.add( object );
101 }
102 }else{
103 if( !morpher.supports( object.getClass() ) ){
104 throw new MorphException( object.getClass() + " is not supported" );
105 }
106 try{
107 list.add( morphMethod.invoke( morpher, new Object[] { object } ) );
108 }
109 catch( MorphException me ){
110 throw me;
111 }
112 catch( Exception e ){
113 throw new MorphException( e );
114 }
115 }
116 }
117
118 return list;
119 }
120
121 public Class morphsTo()
122 {
123 return List.class;
124 }
125
126 public boolean supports( Class clazz )
127 {
128 return clazz != null && List.class.isAssignableFrom( clazz );
129 }
130
131 private void setMorpher( Morpher morpher )
132 {
133 if( morpher == null ){
134 throw new IllegalArgumentException( "morpher can not be null" );
135 }
136 this.morpher = morpher;
137
138
139 try{
140 morphMethod = morpher.getClass()
141 .getDeclaredMethod( "morph", new Class[] { Object.class } );
142 }
143 catch( NoSuchMethodException nsme ){
144 throw new IllegalArgumentException( nsme.getMessage() );
145 }
146 }
147 }