1 7 package java.beans; 8 9 import java.util.HashMap ; 10 import java.util.IdentityHashMap ; 11 import java.util.Map ; 12 13 25 class NameGenerator { 26 27 private Map valueToName; 28 private Map nameToCount; 29 30 public NameGenerator() { 31 valueToName = new IdentityHashMap (); 32 nameToCount = new HashMap (); 33 } 34 35 39 public void clear() { 40 valueToName.clear(); 41 nameToCount.clear(); 42 } 43 44 47 public static String unqualifiedClassName(Class type) { 48 if (type.isArray()) { 49 return unqualifiedClassName(type.getComponentType())+"Array"; 50 } 51 String name = type.getName(); 52 return name.substring(name.lastIndexOf('.')+1); 53 } 54 55 58 public static String capitalize(String name) { 59 if (name == null || name.length() == 0) { 60 return name; 61 } 62 return name.substring(0, 1).toUpperCase() + name.substring(1); 63 } 64 65 73 public String instanceName(Object instance) { 74 if (instance == null) { 75 return "null"; 76 } 77 if (instance instanceof Class ) { 78 return unqualifiedClassName((Class )instance); 79 } 80 else { 81 String result = (String )valueToName.get(instance); 82 if (result != null) { 83 return result; 84 } 85 Class type = instance.getClass(); 86 String className = unqualifiedClassName(type); 87 88 Object size = nameToCount.get(className); 89 int instanceNumber = (size == null) ? 0 : ((Integer )size).intValue() + 1; 90 nameToCount.put(className, new Integer (instanceNumber)); 91 92 result = className + instanceNumber; 93 valueToName.put(instance, result); 94 return result; 95 } 96 } 97 } 98 | Popular Tags |