1 16 package org.apache.cocoon.util; 17 18 import java.lang.reflect.Field ; 19 import java.lang.reflect.Method ; 20 import java.util.Map ; 21 22 26 public final class ReflectionUtils { 27 28 public interface Matcher { 29 boolean matches(final String pName); 30 } 31 32 public interface Indexer { 33 void put(final Map pMap, final String pKey, final Object pObject); 34 } 35 36 private static DefaultIndexer defaultIndexer = new DefaultIndexer(); 37 private static DefaultMatcher defaultMatcher = new DefaultMatcher(); 38 39 private static class DefaultMatcher implements Matcher { 40 public boolean matches(final String pName) { 41 return pName.startsWith("do"); 42 } 43 } 44 45 private static class DefaultIndexer implements Indexer { 46 public void put(final Map pMap, final String pKey, final Object pObject) { 47 48 final String name = Character.toLowerCase(pKey.charAt(2)) + pKey.substring(3); 50 51 System.out.println("reflecting " + name); 52 pMap.put(name, pObject); 53 } 54 } 55 56 public static Map discoverFields( 57 final Class pClazz, 58 final Matcher pMatcher 59 ) { 60 61 return discoverFields(pClazz, pMatcher, defaultIndexer); 62 } 63 64 public static Map discoverFields( 65 final Class pClazz 66 ) { 67 68 return discoverFields(pClazz, defaultMatcher, defaultIndexer); 69 } 70 71 public static Map discoverFields( 72 final Class pClazz, 73 final Matcher pMatcher, 74 final Indexer pIndexer 75 ) { 76 77 System.out.println("discovering fields on " + pClazz.getName()); 78 79 final Map result = new HashMap(); 80 81 Class current = pClazz; 82 do { 83 final Field [] fields = current.getDeclaredFields(); 84 for (int i = 0; i < fields.length; i++) { 85 final String fname = fields[i].getName(); 86 if (pMatcher.matches(fname)) { 87 pIndexer.put(result, fname, fields[i]); 88 } 89 } 90 current = current.getSuperclass(); 91 } while(current != null); 92 93 return result; 94 } 95 96 97 public static Map discoverMethods( 98 final Class pClazz, 99 final Matcher pMatcher 100 ) { 101 102 return discoverMethods(pClazz, pMatcher, defaultIndexer); 103 } 104 105 public static Map discoverMethods( 106 final Class pClazz 107 ) { 108 109 return discoverMethods(pClazz, defaultMatcher, defaultIndexer); 110 } 111 112 public static Map discoverMethods( 113 final Class pClazz, 114 final Matcher pMatcher, 115 final Indexer pIndexer 116 ) { 117 118 System.out.println("discovering methods on " + pClazz.getName()); 119 120 final Map result = new HashMap(); 121 122 Class current = pClazz; 123 do { 124 final Method [] methods = current.getDeclaredMethods(); 125 for (int i = 0; i < methods.length; i++) { 126 final String mname = methods[i].getName(); 127 if (pMatcher.matches(mname)) { 128 pIndexer.put(result, mname, methods[i]); 129 } 130 } 131 current = current.getSuperclass(); 132 } while(current != null); 133 134 return result; 135 } 136 137 } 138 | Popular Tags |