KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > portal > format > template > TemplateUtils


1 /*****************************************
2  * *
3  * JBoss Portal: The OpenSource Portal *
4  * *
5  * Distributable under LGPL license. *
6  * See terms of license at gnu.org. *
7  * *
8  *****************************************/

9
10 package org.jboss.portal.format.template;
11
12 import java.lang.reflect.Field JavaDoc;
13 import java.lang.reflect.Modifier JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.List JavaDoc;
16
17 import org.apache.log4j.Logger;
18
19
20 /**
21  * various methods to assist with using templates
22  *
23  * @version <code>$Revision: 1.2 $</code>
24  */

25 public class TemplateUtils
26 {
27    /**
28     * collect the fields out of any class that match the specified prefix. this
29     * is useful for getting the list of constants whose values represent
30     * template names
31     *
32     * @param clazz class to collect fields out from
33     * @param prefix prefix to match fields against
34     *
35     * @return 2 dimensional array - first dimension contains number of objects,
36     * second dimesion contains field name (a[0]) and value (a[1]).
37     */

38    public static String JavaDoc[][] collectFields(Class JavaDoc clazz, String JavaDoc prefix)
39    {
40       Field JavaDoc[] fields = clazz.getDeclaredFields();
41       List JavaDoc values = new ArrayList JavaDoc(fields.length);
42
43       for (int i = 0; i < fields.length; i++)
44       {
45          Field JavaDoc field = fields[i];
46          int modifier = field.getModifiers();
47
48          if (field.getName().startsWith(prefix) && Modifier.isFinal(modifier)
49              && Modifier.isPublic(modifier) && Modifier.isStatic(modifier))
50          {
51             /*
52              * stick the field name and value into a String[] and then
53              * add it to the array list
54              */

55             try
56             {
57                values.add(
58                   new String JavaDoc[] { field.getName(), (String JavaDoc) field.get(null) });
59             }
60             catch (Exception JavaDoc ignore)
61             {
62                // this swallows run-time exceptions as well - ??
63
Logger.getLogger(clazz).error("", ignore);
64             }
65          }
66       }
67
68       /*
69        * return the the list of String[] objects containing the field
70        * name/values as a 2-dimension array
71        */

72       return (String JavaDoc[][]) values.toArray(new String JavaDoc[values.size()][]);
73    }
74 }
75
Popular Tags