1 3 package org.jmock.core; 4 5 import java.lang.reflect.Array ; 6 import java.lang.reflect.Proxy ; 7 import java.util.Collection ; 8 9 10 public class Formatting 11 { 12 public static String toReadableString( Object element ) { 13 if (element == null) { 14 return "null"; 15 } else if (Proxy.isProxyClass(element.getClass())) { 16 return unpackProxy(element).toString(); 17 } else if (element.getClass().isArray()) { 18 return join(element, new StringBuffer ()).toString(); 19 } else { 20 return element.toString(); 21 } 22 } 23 24 private static Object unpackProxy( Object element ) { 25 Object invocationHandler = Proxy.getInvocationHandler(element); 26 return (invocationHandler instanceof DynamicMock 27 ? invocationHandler 28 : element); 29 } 30 31 public static StringBuffer join( Object array, StringBuffer buf ) { 32 return join(array, buf, "[", "]"); 33 } 34 35 public static StringBuffer join( Collection collection, StringBuffer buf, String prefix, String postfix ) { 36 return join(collection.toArray(), buf, prefix, postfix); 37 } 38 39 public static StringBuffer join( Collection collection, StringBuffer buf, 40 String prefix, String separator, String postfix ) { 41 return join(collection.toArray(), buf, prefix, separator, postfix); 42 } 43 44 public static StringBuffer join( Object array, StringBuffer buf, String prefix, String postfix ) { 45 return join(array, buf, prefix, ", ", postfix); 46 } 47 48 public static StringBuffer join( Object array, StringBuffer buf, 49 String prefix, String separator, String postfix ) { 50 buf.append(prefix); 51 for (int i = 0; i < Array.getLength(array); i++) { 52 if (i > 0) buf.append(separator); 53 54 Object element = Array.get(array, i); 55 56 if (null == element) { 57 buf.append("<null>"); 58 } else if (element.getClass().isArray()) { 59 join(element, buf); 60 } else { 61 buf.append("<"); 62 buf.append(toReadableString(element)); 63 buf.append(">"); 64 } 65 } 66 buf.append(postfix); 67 return buf; 68 } 69 70 public static String classShortName( Class c ) { 71 String fullTypeName = c.getName(); 72 return fullTypeName.substring(Math.max(fullTypeName.lastIndexOf('.'), fullTypeName.lastIndexOf('$')) + 1); 73 } 74 } | Popular Tags |