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 org.apache.log4j.Priority;
21 import org.apache.log4j.helpers.LogLog;
22
23 import java.beans.BeanInfo;
24 import java.beans.IntrospectionException;
25 import java.beans.Introspector;
26 import java.beans.PropertyDescriptor;
27 import java.io.InterruptedIOException;
28 import java.lang.reflect.InvocationTargetException;
29 import java.lang.reflect.Method;
30
31
32
33
34
35
36
37 public class PropertyGetter {
38 protected static final Object[] NULL_ARG = new Object[] {};
39 protected Object obj;
40 protected PropertyDescriptor[] props;
41
42 public interface PropertyCallback {
43 void foundProperty(Object obj, String prefix, String name, Object value);
44 }
45
46
47
48
49
50
51
52
53 public
54 PropertyGetter(Object obj) throws IntrospectionException {
55 BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
56 props = bi.getPropertyDescriptors();
57 this.obj = obj;
58 }
59
60 public
61 static
62 void getProperties(Object obj, PropertyCallback callback, String prefix) {
63 try {
64 new PropertyGetter(obj).getProperties(callback, prefix);
65 } catch (IntrospectionException ex) {
66 LogLog.error("Failed to introspect object " + obj, ex);
67 }
68 }
69
70 public
71 void getProperties(PropertyCallback callback, String prefix) {
72 for (int i = 0; i < props.length; i++) {
73 Method getter = props[i].getReadMethod();
74 if (getter == null) continue;
75 if (!isHandledType(getter.getReturnType())) {
76
77 continue;
78 }
79 String name = props[i].getName();
80 try {
81 Object result = getter.invoke(obj, NULL_ARG);
82
83 if (result != null) {
84 callback.foundProperty(obj, prefix, name, result);
85 }
86 } catch (IllegalAccessException ex) {
87 LogLog.warn("Failed to get value of property " + name);
88 } catch (InvocationTargetException ex) {
89 if (ex.getTargetException() instanceof InterruptedException
90 || ex.getTargetException() instanceof InterruptedIOException) {
91 Thread.currentThread().interrupt();
92 }
93 LogLog.warn("Failed to get value of property " + name);
94 } catch (RuntimeException ex) {
95 LogLog.warn("Failed to get value of property " + name);
96 }
97 }
98 }
99
100 protected
101 boolean isHandledType(Class type) {
102 return String.class.isAssignableFrom(type) ||
103 Integer.TYPE.isAssignableFrom(type) ||
104 Long.TYPE.isAssignableFrom(type) ||
105 Boolean.TYPE.isAssignableFrom(type) ||
106 Priority.class.isAssignableFrom(type);
107 }
108 }