1 16 17 package org.apache.log4j.config; 18 19 import java.beans.*; 20 import java.lang.reflect.*; 21 import org.apache.log4j.Priority; 22 import org.apache.log4j.helpers.LogLog; 23 24 25 30 public class PropertyGetter { 31 protected static final Object [] NULL_ARG = new Object [] {}; 32 protected Object obj; 33 protected PropertyDescriptor[] props; 34 35 public interface PropertyCallback { 36 void foundProperty(Object obj, String prefix, String name, Object value); 37 } 38 39 46 public 47 PropertyGetter(Object obj) throws IntrospectionException { 48 BeanInfo bi = Introspector.getBeanInfo(obj.getClass()); 49 props = bi.getPropertyDescriptors(); 50 this.obj = obj; 51 } 52 53 public 54 static 55 void getProperties(Object obj, PropertyCallback callback, String prefix) { 56 try { 57 new PropertyGetter(obj).getProperties(callback, prefix); 58 } catch (IntrospectionException ex) { 59 LogLog.error("Failed to introspect object " + obj, ex); 60 } 61 } 62 63 public 64 void getProperties(PropertyCallback callback, String prefix) { 65 for (int i = 0; i < props.length; i++) { 66 Method getter = props[i].getReadMethod(); 67 if (getter == null) continue; 68 if (!isHandledType(getter.getReturnType())) { 69 continue; 71 } 72 String name = props[i].getName(); 73 try { 74 Object result = getter.invoke(obj, NULL_ARG); 75 if (result != null) { 77 callback.foundProperty(obj, prefix, name, result); 78 } 79 } catch (Exception ex) { 80 LogLog.warn("Failed to get value of property " + name); 81 } 82 } 83 } 84 85 protected 86 boolean isHandledType(Class type) { 87 return String .class.isAssignableFrom(type) || 88 Integer.TYPE.isAssignableFrom(type) || 89 Long.TYPE.isAssignableFrom(type) || 90 Boolean.TYPE.isAssignableFrom(type) || 91 Priority.class.isAssignableFrom(type); 92 } 93 } 94 | Popular Tags |