View Javadoc

1   package net.sourceforge.pmd.properties;
2   
3   import net.sourceforge.pmd.util.ClassUtil;
4   
5   
6   /**
7    * Defines a property that supports class types, even for primitive values!
8    * 
9    * @author Brian Remedios
10   * @version $Revision$
11   */
12  public class TypeProperty extends StringProperty {
13  	
14  	private static final char delimiter = '|';
15  	
16  	/**
17  	 * Constructor for TypeProperty.
18  	 * @param theName String
19  	 * @param theDescription String
20  	 * @param theDefault Class
21  	 * @param theUIOrder float
22  	 */
23  	public TypeProperty(String theName, String theDescription, Class theDefault, float theUIOrder) {
24  		super(theName, theDescription, theDefault, theUIOrder, delimiter);
25  		
26  		maxValueCount(1);
27  	}
28  
29  	/**
30  	 * Constructor for TypeProperty.
31  	 * @param theName String
32  	 * @param theDescription String
33  	 * @param theDefaults Class[]
34  	 * @param theUIOrder float
35  	 */
36  	public TypeProperty(String theName, String theDescription, Class[] theDefaults, float theUIOrder) {
37  		super(theName, theDescription, theDefaults, theUIOrder, delimiter);
38  		
39  		maxValueCount(Integer.MAX_VALUE);
40  	}
41  	
42  	/**
43  	 * Method type.
44  	 * @return Class
45  	 * @see net.sourceforge.pmd.PropertyDescriptor#type()
46  	 */
47  	public Class<Class> type() {
48  		return Class.class;
49  	}
50  
51  	/**
52  	 * Method asString.
53  	 * @param value Object
54  	 * @return String
55  	 */
56  	protected String asString(Object value) {
57  		return value == null ? "" : ((Class)value).getName();
58  	}
59  	
60  	/**
61  	 * Method classFrom.
62  	 * @param className String
63  	 * @return Class
64  	 */
65  	private Class classFrom(String className) {
66  		
67  		Class cls = ClassUtil.getTypeFor(className);
68  		if (cls != null) return cls;
69  		
70  		try {
71  			return Class.forName(className);
72  			} catch (Exception ex) {
73  				throw new IllegalArgumentException(className);
74  				}
75  	}
76  	
77  	/**
78  	 * Method valueFrom.
79  	 * @param valueString String
80  	 * @return Object
81  	 * @see net.sourceforge.pmd.PropertyDescriptor#valueFrom(String)
82  	 */
83  	public Object valueFrom(String valueString) {
84  		
85  		if (maxValueCount() == 1) return classFrom(valueString);
86  		
87  		String[] values = (String[])super.valueFrom(valueString);
88  		
89  		Class[] classes = new Class[values.length];
90  		for (int i=0; i<values.length; i++) classes[i] = classFrom(values[i]);
91  		return classes;
92  	}
93  	
94  	/**
95  	 * Neutralize unwanted superclass functionality that will result 
96  	 * in a class cast exception.
97  	 * 
98  	 * @param value Object
99  	 * @return String
100 	 */
101 	protected String valueErrorFor(Object value) {		
102 		return null;
103 	}
104 }