1. /* ====================================================================
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowledgement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowledgement may appear in the software itself,
  24. * if and wherever such third-party acknowledgements normally appear.
  25. *
  26. * 4. The names "The Jakarta Project", "Commons", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Software Foundation.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.commons.lang.builder;
  55. import java.lang.reflect.AccessibleObject;
  56. import java.lang.reflect.Field;
  57. import java.lang.reflect.Modifier;
  58. import java.util.HashSet;
  59. import java.util.Set;
  60. import org.apache.commons.lang.ClassUtils;
  61. /**
  62. * <p>Assists in implementing {@link Object#toString()} methods using reflection.</p>
  63. *
  64. * <p>This class uses reflection to determine the fields to append.
  65. * Because these fields are usually private, the class
  66. * uses <code>AccessibleObject.setAccessible</code> to
  67. * change the visibility of the fields. This will fail under a security manager,
  68. * unless the appropriate permissions are set up correctly.</p>
  69. *
  70. * <p>A typical invocation for this method would look like:</p>
  71. * <pre>
  72. * public String toString() {
  73. * return ReflectionToStringBuilder.toString(this);
  74. * }</pre>
  75. *
  76. * <p>You can also use the builder to debug 3rd party objects:</p>
  77. * <pre>
  78. * System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));</pre>
  79. *
  80. * <p>A subclass can control field output by overriding the methods:
  81. * <ul>
  82. * <li>{@link #accept(java.lang.reflect.Field)}</li>
  83. * <li>{@link #getValue(java.lang.reflect.Field)}</li>
  84. * </ul>
  85. * </p>
  86. * <p>For example, this method does <i>not</i> include the <code>password</code> field in the returned
  87. * <code>String</code>:</p>
  88. * <pre>
  89. * public String toString() {
  90. * return (new ReflectionToStringBuilder(this) {
  91. * protected boolean accept(Field f) {
  92. * return super.accept(f) && !f.getName().equals("password");
  93. * }
  94. * }).toString();
  95. * }</pre>
  96. *
  97. * <p>The exact format of the <code>toString</code> is determined by
  98. * the {@link ToStringStyle} passed into the constructor.</p>
  99. *
  100. * @author Gary Gregory
  101. * @author Stephen Colebourne
  102. * @author Pete Gieser
  103. * @since 2.0
  104. * @version $Id: ReflectionToStringBuilder.java,v 1.10 2003/08/23 00:21:49 ggregory Exp $
  105. */
  106. public class ReflectionToStringBuilder extends ToStringBuilder {
  107. /**
  108. * <p>A registry of objects used by <code>reflectionToString</code> methods
  109. * to detect cyclical object references and avoid infinite loops.</p>
  110. */
  111. private static ThreadLocal registry = new ThreadLocal() {
  112. protected synchronized Object initialValue() {
  113. // The HashSet implementation is not synchronized,
  114. // which is just what we need here.
  115. return new HashSet();
  116. }
  117. };
  118. /**
  119. * <p>Returns the registry of objects being traversed by the
  120. * <code>reflectionToString</code> methods in the current thread.</p>
  121. *
  122. * @return Set the registry of objects being traversed
  123. */
  124. static Set getRegistry() {
  125. return (Set) registry.get();
  126. }
  127. /**
  128. * <p>Returns <code>true</code> if the registry contains the given object.
  129. * Used by the reflection methods to avoid infinite loops.</p>
  130. *
  131. * @param value The object to lookup in the registry.
  132. * @return boolean <code>true</code> if the registry contains the given object.
  133. */
  134. static boolean isRegistered(Object value) {
  135. return getRegistry().contains(value);
  136. }
  137. /**
  138. * <p>Registers the given object.
  139. * Used by the reflection methods to avoid infinite loops.</p>
  140. *
  141. * @param value The object to register.
  142. */
  143. static void register(Object value) {
  144. getRegistry().add(value);
  145. }
  146. /**
  147. * <p>This method uses reflection to build a suitable
  148. * <code>toString</code> using the default <code>ToStringStyle</code>.
  149. *
  150. * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
  151. * fields. This means that it will throw a security exception if run
  152. * under a security manager, if the permissions are not set up correctly.
  153. * It is also not as efficient as testing explicitly.</p>
  154. *
  155. * <p>Transient members will be not be included, as they are likely derived.
  156. * Static fields will not be included. Superclass fields will be appended.</p>
  157. *
  158. * @param object the Object to be output
  159. * @return the String result
  160. * @throws IllegalArgumentException if the Object is <code>null</code>
  161. */
  162. public static String toString(Object object) {
  163. return toString(object, null, false, null);
  164. }
  165. /**
  166. * <p>This method uses reflection to build a suitable
  167. * <code>toString</code>.</p>
  168. *
  169. * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
  170. * fields. This means that it will throw a security exception if run
  171. * under a security manager, if the permissions are not set up correctly.
  172. * It is also not as efficient as testing explicitly.</p>
  173. *
  174. * <p>Transient members will be not be included, as they are likely derived.
  175. * Static fields will not be included. Superclass fields will be appended.</p>
  176. *
  177. * <p>If the style is <code>null</code>, the default
  178. * <code>ToStringStyle</code> is used.</p>
  179. *
  180. * @param object the Object to be output
  181. * @param style the style of the <code>toString</code> to create,
  182. * may be <code>null</code>
  183. * @return the String result
  184. * @throws IllegalArgumentException if the Object or
  185. * <code>ToStringStyle</code> is <code>null</code>
  186. */
  187. public static String toString(Object object, ToStringStyle style) {
  188. return toString(object, style, false, null);
  189. }
  190. /**
  191. * <p>This method uses reflection to build a suitable
  192. * <code>toString</code>.</p>
  193. *
  194. * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
  195. * fields. This means that it will throw a security exception if run
  196. * under a security manager, if the permissions are not set up correctly.
  197. * It is also not as efficient as testing explicitly. </p>
  198. *
  199. * <p>If the <code>outputTransients</code> is <code>true</code>,
  200. * transient members will be output, otherwise they are ignored,
  201. * as they are likely derived fields, and not part of the value of the
  202. * Object.</p>
  203. *
  204. * <p>Static fields will not be included. Superclass fields will be appended.</p>
  205. *
  206. * <p>If the style is <code>null</code>, the default
  207. * <code>ToStringStyle</code> is used.</p>
  208. *
  209. * @param object the Object to be output
  210. * @param style the style of the <code>toString</code> to create,
  211. * may be <code>null</code>
  212. * @param outputTransients whether to include transient fields
  213. * @return the String result
  214. * @throws IllegalArgumentException if the Object is <code>null</code>
  215. */
  216. public static String toString(Object object, ToStringStyle style, boolean outputTransients) {
  217. return toString(object, style, outputTransients, null);
  218. }
  219. /**
  220. * <p>This method uses reflection to build a suitable
  221. * <code>toString</code>.</p>
  222. *
  223. * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
  224. * fields. This means that it will throw a security exception if run
  225. * under a security manager, if the permissions are not set up correctly.
  226. * It is also not as efficient as testing explicitly. </p>
  227. *
  228. * <p>If the <code>outputTransients</code> is <code>true</code>,
  229. * transient members will be output, otherwise they are ignored,
  230. * as they are likely derived fields, and not part of the value of the
  231. * Object.</p>
  232. *
  233. * <p>Static fields will not be included. Superclass fields will be appended
  234. * up to and including the specified superclass. A null superclass is treated
  235. * as <code>java.lang.Object</code>.</p>
  236. *
  237. * <p>If the style is <code>null</code>, the default
  238. * <code>ToStringStyle</code> is used.</p>
  239. *
  240. * @param object the Object to be output
  241. * @param style the style of the <code>toString</code> to create,
  242. * may be <code>null</code>
  243. * @param outputTransients whether to include transient fields
  244. * @param reflectUpToClass the superclass to reflect up to (inclusive),
  245. * may be <code>null</code>
  246. * @return the String result
  247. * @throws IllegalArgumentException if the Object is <code>null</code>
  248. */
  249. public static String toString(
  250. Object object,
  251. ToStringStyle style,
  252. boolean outputTransients,
  253. Class reflectUpToClass) {
  254. return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients).toString();
  255. }
  256. /**
  257. * <p>Unregisters the given object.</p>
  258. *
  259. * <p>Used by the reflection methods to avoid infinite loops.</p>
  260. *
  261. * @param value The object to unregister.
  262. */
  263. static void unregister(Object value) {
  264. getRegistry().remove(value);
  265. }
  266. /**
  267. * Whether or not to append transient fields.
  268. */
  269. private boolean appendTransients = false;
  270. /**
  271. * The last super class to stop appending fields for.
  272. */
  273. private Class upToClass = null;
  274. /**
  275. * <p>Constructor.</p>
  276. *
  277. * <p>This constructor outputs using the default style set with
  278. * <code>setDefaultStyle</code>.</p>
  279. *
  280. * @param object the Object to build a <code>toString</code> for,
  281. * must not be <code>null</code>
  282. * @throws IllegalArgumentException if the Object passed in is
  283. * <code>null</code>
  284. */
  285. public ReflectionToStringBuilder(Object object) {
  286. super(object);
  287. }
  288. /**
  289. * <p>Constructor.</p>
  290. *
  291. * <p>If the style is <code>null</code>, the default style is used.</p>
  292. *
  293. * @param object the Object to build a <code>toString</code> for,
  294. * must not be <code>null</code>
  295. * @param style the style of the <code>toString</code> to create,
  296. * may be <code>null</code>
  297. * @throws IllegalArgumentException if the Object passed in is
  298. * <code>null</code>
  299. */
  300. public ReflectionToStringBuilder(Object object, ToStringStyle style) {
  301. super(object, style);
  302. }
  303. /**
  304. * <p>Constructor.</p>
  305. *
  306. * <p>If the style is <code>null</code>, the default style is used.</p>
  307. *
  308. * <p>If the buffer is <code>null</code>, a new one is created.</p>
  309. *
  310. * @param object the Object to build a <code>toString</code> for,
  311. * must not be <code>null</code>
  312. * @param style the style of the <code>toString</code> to create,
  313. * may be <code>null</code>
  314. * @param buffer the <code>StringBuffer</code> to populate, may be
  315. * <code>null</code>
  316. * @throws IllegalArgumentException if the Object passed in is
  317. * <code>null</code>
  318. */
  319. public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
  320. super(object, style, buffer);
  321. }
  322. /**
  323. * Constructor.
  324. *
  325. * @param object the Object to build a <code>toString</code> for,
  326. * must not be <code>null</code>
  327. * @param style the style of the <code>toString</code> to create,
  328. * may be <code>null</code>
  329. * @param buffer the <code>StringBuffer</code> to populate, may be
  330. * <code>null</code>
  331. * @param reflectUpToClass the superclass to reflect up to (inclusive),
  332. * may be <code>null</code>
  333. * @param outputTransients whether to include transient fields
  334. */
  335. public ReflectionToStringBuilder(
  336. Object object,
  337. ToStringStyle style,
  338. StringBuffer buffer,
  339. Class reflectUpToClass,
  340. boolean outputTransients) {
  341. super(object, style, buffer);
  342. this.setUpToClass(reflectUpToClass);
  343. this.setAppendTransients(outputTransients);
  344. }
  345. /**
  346. * Returns whether or not to append the given <code>Field</code>.
  347. * <ul>
  348. * <li>Static fields are not appended.</li>
  349. * <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
  350. * <li>Inner class fields are not appened.</li>
  351. * </ul>
  352. * @param field The Field to test.
  353. * @return Whether or not to append the given <code>Field</code>.
  354. */
  355. protected boolean accept(Field field) {
  356. String fieldName = field.getName();
  357. return (fieldName.indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) == -1)
  358. && (this.isAppendTransients() || !Modifier.isTransient(field.getModifiers()))
  359. && (!Modifier.isStatic(field.getModifiers()));
  360. }
  361. /**
  362. * <p>Appends the fields and values defined by the given object of the
  363. * given Class.</p>
  364. *
  365. * <p>If a cycle is detected as an object is "toString()'ed",
  366. * such an object is rendered as if <code>Object.toString()</code>
  367. * had been called and not implemented by the object.</p>
  368. *
  369. * @param clazz The class of object parameter
  370. */
  371. protected void appendFieldsIn(Class clazz) {
  372. if (isRegistered(this.getObject())) {
  373. // The object has already been appended, therefore we have an object cycle.
  374. // Append a simple Object.toString style string. The field name is already appended at this point.
  375. this.appendAsObjectToString(this.getObject());
  376. return;
  377. }
  378. try {
  379. this.registerObject();
  380. if (clazz.isArray()) {
  381. this.reflectionAppendArray(this.getObject());
  382. return;
  383. }
  384. Field[] fields = clazz.getDeclaredFields();
  385. AccessibleObject.setAccessible(fields, true);
  386. for (int i = 0; i < fields.length; i++) {
  387. Field field = fields[i];
  388. String fieldName = field.getName();
  389. if (this.accept(field)) {
  390. try {
  391. // Warning: Field.get(Object) creates wrappers objects for primitive types.
  392. Object fieldValue = this.getValue(field);
  393. if (isRegistered(fieldValue) && !field.getType().isPrimitive()) {
  394. // A known field value has already been appended, therefore we have an object cycle,
  395. // append a simple Object.toString style string.
  396. this.getStyle().appendFieldStart(this.getStringBuffer(), fieldName);
  397. this.appendAsObjectToString(fieldValue);
  398. // The recursion out of
  399. // builder.append(fieldName, fieldValue);
  400. // below will append the field
  401. // end marker.
  402. } else {
  403. try {
  404. this.registerObject();
  405. this.append(fieldName, fieldValue);
  406. } finally {
  407. this.unregisterObject();
  408. }
  409. }
  410. } catch (IllegalAccessException ex) {
  411. //this can't happen. Would get a Security exception instead
  412. //throw a runtime exception in case the impossible happens.
  413. throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
  414. }
  415. }
  416. }
  417. } finally {
  418. this.unregisterObject();
  419. }
  420. }
  421. /**
  422. * <p>Gets the last super class to stop appending fields for.</p>
  423. *
  424. * @return The last super class to stop appending fields for.
  425. */
  426. public Class getUpToClass() {
  427. return this.upToClass;
  428. }
  429. /**
  430. * <p>Calls <code>java.lang.reflect.Field.get(Object)</code>.</p>
  431. *
  432. * @see java.lang.reflect.Field#get(Object)
  433. * @throws IllegalArgumentException
  434. * @throws IllegalAccessException
  435. */
  436. protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {
  437. return field.get(this.getObject());
  438. }
  439. /**
  440. * <p>Gets whether or not to append transient fields.</p>
  441. *
  442. * @return Whether or not to append transient fields.
  443. */
  444. public boolean isAppendTransients() {
  445. return this.appendTransients;
  446. }
  447. /**
  448. * <p>Append to the <code>toString</code> an <code>Object</code>
  449. * array.</p>
  450. *
  451. * @param array the array to add to the <code>toString</code>
  452. * @return this
  453. */
  454. public ToStringBuilder reflectionAppendArray(Object array) {
  455. this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array);
  456. return this;
  457. }
  458. /**
  459. * <p>Registers this builder's source object to avoid infinite
  460. * loops when processing circular object references.</p>
  461. */
  462. void registerObject() {
  463. register(this.getObject());
  464. }
  465. /**
  466. * <p>Sets whether or not to append transient fields.</p>
  467. *
  468. * @param appendTransients Whether or not to append transient fields.
  469. */
  470. public void setAppendTransients(boolean appendTransients) {
  471. this.appendTransients = appendTransients;
  472. }
  473. /**
  474. * <p>Sets the last super class to stop appending fields for.</p>
  475. *
  476. * @param clazz The last super class to stop appending fields for.
  477. */
  478. public void setUpToClass(Class clazz) {
  479. this.upToClass = clazz;
  480. }
  481. /**
  482. * <p>Gets the String built by this builder.</p>
  483. *
  484. * @return the built string
  485. */
  486. public String toString() {
  487. if (this.getObject() == null) {
  488. return this.getStyle().getNullText();
  489. }
  490. Class clazz = this.getObject().getClass();
  491. this.appendFieldsIn(clazz);
  492. while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) {
  493. clazz = clazz.getSuperclass();
  494. this.appendFieldsIn(clazz);
  495. }
  496. return super.toString();
  497. }
  498. /**
  499. * <p>Unegisters this builder's source object to avoid infinite
  500. * loops when processing circular object references.</p>
  501. */
  502. void unregisterObject() {
  503. unregister(this.getObject());
  504. }
  505. }