View Javadoc

1   /*
2    * Copyright 2004-2005, 2007 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
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  }