1 /*
2 * Copyright 2006-2007 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.ezmorph.array;
18
19 import java.lang.reflect.Array;
20
21 import net.sf.ezmorph.ObjectMorpher;
22
23 /**
24 * Base class for array Morphers.
25 *
26 * @author Andres Almiray <aalmiray@users.sourceforge.net>
27 */
28 public abstract class AbstractArrayMorpher implements ObjectMorpher
29 {
30 private boolean useDefault = false;
31
32 public AbstractArrayMorpher()
33 {
34 }
35
36 /**
37 * @param useDefault if morph() should return a default value if the value to
38 * be morphed is null
39 */
40 public AbstractArrayMorpher( boolean useDefault )
41 {
42 this.useDefault = useDefault;
43 }
44
45 /**
46 * Returns if this morpher will use a default value.
47 */
48 public boolean isUseDefault()
49 {
50 return useDefault;
51 }
52
53 /**
54 * Sets if this morpher will use a default value.
55 */
56 public void setUseDefault( boolean useDefault )
57 {
58 this.useDefault = useDefault;
59 }
60
61 public boolean supports( Class clazz )
62 {
63 return clazz.isArray();
64 }
65
66 /**
67 * Creates an array representing the dimensions for comversion.
68 */
69 protected int[] createDimensions( int length, int initial )
70 {
71 Object dims = Array.newInstance( int.class, length );
72 Array.set( dims, 0, new Integer( initial ) );
73 return (int[]) dims;
74 }
75
76 /**
77 * Returns the number of dimensions in an array class.
78 */
79 protected int getDimensions( Class arrayClass )
80 {
81 if( arrayClass == null || !arrayClass.isArray() ){
82 return 0;
83 }
84
85 return 1 + getDimensions( arrayClass.getComponentType() );
86 }
87 }