View Javadoc

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.object;
18  
19  import net.sf.ezmorph.MorphException;
20  import net.sf.ezmorph.ObjectMorpher;
21  
22  /**
23   * Morphs to a String.<br>
24   * This morpher is a singleton.
25   *
26   * @author Andres Almiray <aalmiray@users.sourceforge.net>
27   */
28  public final class StringMorpher implements ObjectMorpher
29  {
30     private static final StringMorpher INSTANCE = new StringMorpher();
31  
32     /**
33      * Returns the singleton instance
34      */
35     public static StringMorpher getInstance()
36     {
37        return INSTANCE;
38     }
39  
40     private StringMorpher()
41     {
42     }
43  
44     public boolean equals( Object obj )
45     {
46        return INSTANCE == obj;
47     }
48  
49     public int hashCode()
50     {
51        return 42 + getClass().hashCode();
52     }
53  
54     public Object morph( Object value )
55     {
56        if( value == null ){
57           return null;
58        }
59  
60        if( !supports( value.getClass() ) ){
61           throw new MorphException( "Class not supported. " + value.getClass() );
62        }
63  
64        if( String.class.isAssignableFrom( value.getClass() ) ){
65           return (String) value;
66        }
67  
68        return String.valueOf( value );
69     }
70  
71     public Class morphsTo()
72     {
73        return String.class;
74     }
75  
76     public boolean supports( Class clazz )
77     {
78        return !clazz.isArray();
79     }
80  }