1. /*
  2. * @(#)NameGenerator.java 1.9 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.beans;
  8. import java.util.HashMap;
  9. import java.util.IdentityHashMap;
  10. import java.util.Map;
  11. /**
  12. * A utility class which generates unique names for object instances.
  13. * The name will be a concatenation of the unqualified class name
  14. * and an instance number.
  15. * <p>
  16. * For example, if the first object instance javax.swing.JButton
  17. * is passed into <code>instanceName</code> then the returned
  18. * string identifier will be "JButton0".
  19. *
  20. * @version 1.9 12/19/03
  21. * @author Philip Milne
  22. */
  23. class NameGenerator {
  24. private Map valueToName;
  25. private Map nameToCount;
  26. public NameGenerator() {
  27. valueToName = new IdentityHashMap();
  28. nameToCount = new HashMap();
  29. }
  30. /**
  31. * Clears the name cache. Should be called to near the end of
  32. * the encoding cycle.
  33. */
  34. public void clear() {
  35. valueToName.clear();
  36. nameToCount.clear();
  37. }
  38. /**
  39. * Returns the root name of the class.
  40. */
  41. public static String unqualifiedClassName(Class type) {
  42. if (type.isArray()) {
  43. return unqualifiedClassName(type.getComponentType())+"Array";
  44. }
  45. String name = type.getName();
  46. return name.substring(name.lastIndexOf('.')+1);
  47. }
  48. /**
  49. * Returns a String which capitalizes the first letter of the string.
  50. */
  51. public static String capitalize(String name) {
  52. if (name == null || name.length() == 0) {
  53. return name;
  54. }
  55. return name.substring(0, 1).toUpperCase() + name.substring(1);
  56. }
  57. /**
  58. * Returns a unique string which identifies the object instance.
  59. * Invocations are cached so that if an object has been previously
  60. * passed into this method then the same identifier is returned.
  61. *
  62. * @param instance object used to generate string
  63. * @return a unique string representing the object
  64. */
  65. public String instanceName(Object instance) {
  66. if (instance == null) {
  67. return "null";
  68. }
  69. if (instance instanceof Class) {
  70. return unqualifiedClassName((Class)instance);
  71. }
  72. else {
  73. String result = (String)valueToName.get(instance);
  74. if (result != null) {
  75. return result;
  76. }
  77. Class type = instance.getClass();
  78. String className = unqualifiedClassName(type);
  79. Object size = nameToCount.get(className);
  80. int instanceNumber = (size == null) ? 0 : ((Integer)size).intValue() + 1;
  81. nameToCount.put(className, new Integer(instanceNumber));
  82. result = className + instanceNumber;
  83. valueToName.put(instance, result);
  84. return result;
  85. }
  86. }
  87. }