1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.sf.ezmorph.array;
18
19 import java.lang.reflect.Array;
20
21 import net.sf.ezmorph.MorphException;
22 import net.sf.ezmorph.primitive.BooleanMorpher;
23
24 import org.apache.commons.lang.builder.EqualsBuilder;
25 import org.apache.commons.lang.builder.HashCodeBuilder;
26
27
28
29
30
31
32 public final class BooleanArrayMorpher extends AbstractArrayMorpher
33 {
34 private static final Class BOOLEAN_ARRAY_CLASS = boolean[].class;
35 private boolean defaultValue;
36
37 public BooleanArrayMorpher()
38 {
39 super( false );
40 }
41
42
43
44
45 public BooleanArrayMorpher( boolean defaultValue )
46 {
47 super( true );
48 this.defaultValue = defaultValue;
49 }
50
51 public boolean equals( Object obj )
52 {
53 if( this == obj ){
54 return true;
55 }
56 if( obj == null ){
57 return false;
58 }
59
60 if( !(obj instanceof BooleanArrayMorpher) ){
61 return false;
62 }
63
64 BooleanArrayMorpher other = (BooleanArrayMorpher) obj;
65 EqualsBuilder builder = new EqualsBuilder();
66 if( isUseDefault() && other.isUseDefault() ){
67 builder.append( getDefaultValue(), other.getDefaultValue() );
68 return builder.isEquals();
69 }else if( !isUseDefault() && !other.isUseDefault() ){
70 return builder.isEquals();
71 }else{
72 return false;
73 }
74 }
75
76 public boolean getDefaultValue()
77 {
78 return defaultValue;
79 }
80
81 public int hashCode()
82 {
83 HashCodeBuilder builder = new HashCodeBuilder();
84 if( isUseDefault() ){
85 builder.append( getDefaultValue() );
86 }
87 return builder.toHashCode();
88 }
89
90 public Object morph( Object array )
91 {
92 if( array == null ){
93 return null;
94 }
95
96 if( BOOLEAN_ARRAY_CLASS.isAssignableFrom( array.getClass() ) ){
97
98 return (boolean[]) array;
99 }
100
101 if( array.getClass()
102 .isArray() ){
103 int length = Array.getLength( array );
104 int dims = getDimensions( array.getClass() );
105 int[] dimensions = createDimensions( dims, length );
106 Object result = Array.newInstance( boolean.class, dimensions );
107 BooleanMorpher morpher = isUseDefault() ? new BooleanMorpher( defaultValue )
108 : new BooleanMorpher();
109 if( dims == 1 ){
110 for( int index = 0; index < length; index++ ){
111 Array.set( result, index, morpher.morph( Array.get( array, index ) ) ? Boolean.TRUE
112 : Boolean.FALSE );
113 }
114 }else{
115 for( int index = 0; index < length; index++ ){
116 Array.set( result, index, morph( Array.get( array, index ) ) );
117 }
118 }
119 return result;
120 }else{
121 throw new MorphException( "argument is not an array: " + array.getClass() );
122 }
123 }
124
125 public Class morphsTo()
126 {
127 return BOOLEAN_ARRAY_CLASS;
128 }
129 }