View Javadoc

1   package net.sourceforge.jparam;
2   
3   import java.lang.reflect.Field;
4   import java.lang.reflect.Modifier;
5   import java.util.HashMap;
6   import java.util.Map;
7   
8   /***
9    * The constant registry, here all the constant mapping are saved and
10   * dereferenced
11   *  
12   * @author ron_sidi
13   * 
14   */
15  public class ConstantRegistry {
16  	private static ConstantRegistry registry = null;
17  
18  	private Map constantsMap = new HashMap();
19  
20  	private ConstantRegistry() {
21  	}
22  
23  	public static ConstantRegistry getInstance() {
24  		if (registry == null) {
25  			registry = new ConstantRegistry();
26  		}
27  		return registry;
28  	}
29  
30  	public Object getConstant(String name) {
31  		return constantsMap.get(name);
32  	}
33  
34  	public boolean isConstant(String name) {
35  		return constantsMap.containsKey(name);
36  	}
37  
38  	public void registerConstant(String name, Object value) {
39  		constantsMap.put(name, value);
40  	}
41  
42  	public static void clearSingleton() {
43  		registry = null;
44  	}
45  
46  	/***
47  	 * Register all constants defined in the given helper class, a field is
48  	 * considered a valid constant if the following apply:
49  	 * <p>
50  	 * <li>the field is <code>static</code></li>
51  	 * <li>the field is <code>final</code></li>
52  	 * <p>
53  	 * The field name is used as the constant name in JParam and the field
54  	 * static value is defined as the value to replace with
55  	 * 
56  	 * @param helperClass
57  	 */
58  	public void registerHelperClass(Class helperClass) {
59  		Field[] helperClassFields = helperClass.getFields();
60  		for (int i = 0; i < helperClassFields.length; i++) {
61  			Field f = helperClassFields[i];
62  
63  			if (Modifier.isStatic(f.getModifiers())
64  					&& Modifier.isFinal(f.getModifiers())) {
65  				try {
66  					registerConstant(f.getName(), f.get(null));
67  				} catch (IllegalAccessException e) {
68  					System.err
69  							.println("Error registering constant, final static field is not accesible in helper class");
70  				}
71  			}
72  		}
73  	}
74  }