1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.composite.util;
17
18 import java.util.List;
19
20 import net.sf.composite.Defaults;
21 import net.sf.composite.SpecializableComposite;
22 import net.sf.composite.extract.ComponentAccessor;
23 import net.sf.composite.specialize.SpecializationException;
24
25 /***
26 * Utility functions for users of the SimpleComposite package.
27 *
28 * @author Matt Sgarlata
29 * @since Mar 11, 2005
30 */
31 public abstract class CompositeUtils {
32
33 private CompositeUtils() { }
34
35 private static final ComponentAccessor COMPONENT_ACCESSOR = Defaults.createComponentAccessor();
36
37 public static boolean isSpecializable(Object composite, Class type) {
38 Assert.notEmpty(composite, "composite");
39 Assert.notEmpty(composite, "type");
40
41 return composite instanceof SpecializableComposite
42 ? ((SpecializableComposite) composite).isSpecializable(type) : type.isAssignableFrom(composite.getClass());
43 }
44
45 public static Object specialize(Object composite, Class type) {
46 Assert.notEmpty(composite, "composite");
47 Assert.notEmpty(composite, "type");
48
49 if (composite instanceof SpecializableComposite) {
50 return ((SpecializableComposite) composite).specialize(type);
51 }
52 if (type.isAssignableFrom(composite.getClass())) {
53 return composite;
54 }
55 throw new SpecializationException(
56 "The object "
57 + ObjectUtils.getObjectDescription(composite)
58 + " is not an instance of "
59 + ObjectUtils.getObjectDescription(type)
60 + " and cannot be specialized to that type because the"
61 + " object is not a specializable composite");
62 }
63
64 public static String toString(Object composite) {
65 if (composite == null) {
66 return null;
67 }
68 String componentStr = "";
69 List components = COMPONENT_ACCESSOR.getComponents(composite);
70 if (!ObjectUtils.isEmpty(components)) {
71 String[] classNames = new String[components.size()];
72 for (int i=0; i<classNames.length; i++) {
73 classNames[i] = ClassUtils.getUnqualifiedClassName(components.get(i).getClass());
74 }
75 componentStr = "[" + StringUtils.join(classNames, ",") + "]";
76 }
77 return ClassUtils.getUnqualifiedClassName(composite.getClass()) + componentStr;
78 }
79 }