1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.fulcrum.yaafi.framework.util;
21
22
23
24
25
26
27
28
29
30
31
32 public class ToStringBuilder
33 {
34 private StringBuilder buffer = new StringBuilder();
35
36 private int mode;
37 private int attributeCount;
38
39 private static int defaultMode = 0x03;
40
41 public static final int INCLUDE_PACKAGE_PREFIX = 0x1;
42 public static final int INCLUDE_HASHCODE = 0x02;
43
44 public ToStringBuilder(Object target)
45 {
46 this(target, defaultMode);
47 }
48
49 public ToStringBuilder(Object target, int mode)
50 {
51 this.mode = mode;
52
53 appendClassName(target);
54 appendHashCode(target);
55 }
56
57 private void appendHashCode(Object target)
58 {
59 if ((this.mode & INCLUDE_HASHCODE) == 0)
60 return;
61
62 this.buffer.append('@');
63 this.buffer.append(Integer.toHexString(target.hashCode()));
64 }
65
66 private void appendClassName(Object target)
67 {
68 String className = target.getClass().getName();
69
70 if ((this.mode & INCLUDE_PACKAGE_PREFIX) != 0)
71 {
72 this.buffer.append(className);
73 return;
74 }
75
76 int lastdotx = className.lastIndexOf('.');
77
78 this.buffer.append(className.substring(lastdotx + 1));
79 }
80
81 public static int getDefaultMode()
82 {
83 return defaultMode;
84 }
85
86 public static void setDefaultMode(int i)
87 {
88 defaultMode = i;
89 }
90
91
92
93
94
95 public String toString()
96 {
97 if (this.attributeCount > 0)
98 this.buffer.append(']');
99
100 String result = this.buffer.toString();
101
102 this.buffer = null;
103
104 return result;
105 }
106
107 public void append(String attributeName, boolean value)
108 {
109 append(attributeName, String.valueOf(value));
110 }
111
112 public void append(String attributeName, byte value)
113 {
114 append(attributeName, String.valueOf(value));
115
116 }
117 public void append(String attributeName, short value)
118 {
119 append(attributeName, String.valueOf(value));
120 }
121
122 public void append(String attributeName, int value)
123 {
124 append(attributeName, String.valueOf(value));
125 }
126
127 public void append(String attributeName, Object value)
128 {
129 append(attributeName, String.valueOf(value));
130 }
131
132 public void append(String attributeName, String value)
133 {
134 if (this.attributeCount++ == 0)
135 this.buffer.append('[');
136
137 else
138 this.buffer.append(' ');
139
140 this.buffer.append(attributeName);
141
142 this.buffer.append('=');
143
144 this.buffer.append(value);
145 }
146 }