1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.composite.specialize.specializers;
17
18 import java.lang.reflect.Method;
19 import java.util.List;
20
21 import net.sf.composite.util.ContainerUtils;
22
23 /***
24 * <p>Specializes a composite by cloning it and then filtering out components that
25 * are not of the requested <code>specializedType</code>. Since this
26 * specializer relies on cloning, the original composite must implement the
27 * requested <code>specializedType</code>.</p>
28 *
29 * <p>The main benefit of this specializer is performance. The main drawback
30 * is that the composite to be specialized must implement all of the interfaces
31 * to which it may be specialized.</p>
32 *
33 * @author Matt Sgarlata
34 * @since Feb 2, 2006
35 */
36 public class CloningSpecializer extends BaseSpecializer {
37
38 protected boolean isSpecializableImpl(Object composite,
39 Class specializedType) throws Exception {
40 return composite instanceof Cloneable
41 && specializedType.isAssignableFrom(composite.getClass());
42 }
43
44 protected Object specializeImpl(Object composite, Class specializedType) throws Exception {
45 List components = getComponentAccessor().getComponents(composite);
46 List specializedComponents = ContainerUtils.getElementsOfType(components, specializedType);
47
48 Method cloningMethod = composite.getClass().getMethod("clone", (Class[]) null);
49 Object clone = cloningMethod.invoke(composite, (Object[]) null);
50 getComponentAccessor().setComponents(clone, specializedComponents);
51 return clone;
52 }
53
54 }