1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j.config;
19
20 import java.beans.*;
21 import java.lang.reflect.*;
22 import org.apache.log4j.Priority;
23 import org.apache.log4j.helpers.LogLog;
24
25
26 /***
27 Used for inferring configuration information for a log4j's component.
28
29 @author Anders Kristensen
30 */
31 public class PropertyGetter {
32 protected static final Object[] NULL_ARG = new Object[] {};
33 protected Object obj;
34 protected PropertyDescriptor[] props;
35
36 public interface PropertyCallback {
37 void foundProperty(Object obj, String prefix, String name, Object value);
38 }
39
40 /***
41 Create a new PropertyGetter for the specified Object. This is done
42 in prepartion for invoking {@link
43 #getProperties(PropertyGetter.PropertyCallback, String)} one or
44 more times.
45
46 @param obj the object for which to set properties */
47 public
48 PropertyGetter(Object obj) throws IntrospectionException {
49 BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
50 props = bi.getPropertyDescriptors();
51 this.obj = obj;
52 }
53
54 public
55 static
56 void getProperties(Object obj, PropertyCallback callback, String prefix) {
57 try {
58 new PropertyGetter(obj).getProperties(callback, prefix);
59 } catch (IntrospectionException ex) {
60 LogLog.error("Failed to introspect object " + obj, ex);
61 }
62 }
63
64 public
65 void getProperties(PropertyCallback callback, String prefix) {
66 for (int i = 0; i < props.length; i++) {
67 Method getter = props[i].getReadMethod();
68 if (getter == null) continue;
69 if (!isHandledType(getter.getReturnType())) {
70
71 continue;
72 }
73 String name = props[i].getName();
74 try {
75 Object result = getter.invoke(obj, NULL_ARG);
76
77 if (result != null) {
78 callback.foundProperty(obj, prefix, name, result);
79 }
80 } catch (Exception ex) {
81 LogLog.warn("Failed to get value of property " + name);
82 }
83 }
84 }
85
86 protected
87 boolean isHandledType(Class type) {
88 return String.class.isAssignableFrom(type) ||
89 Integer.TYPE.isAssignableFrom(type) ||
90 Long.TYPE.isAssignableFrom(type) ||
91 Boolean.TYPE.isAssignableFrom(type) ||
92 Priority.class.isAssignableFrom(type);
93 }
94 }