View Javadoc

1   /*
2    * Copyright 2011 FatWire Corporation. All Rights Reserved.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of 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,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.fatwire.gst.foundation.controller.support;
17  
18  import java.lang.reflect.Constructor;
19  import java.lang.reflect.InvocationTargetException;
20  import java.lang.reflect.Method;
21  
22  /**
23   * 
24   * @author Dolf Dijkstra
25   * 
26   */
27  public class TemplateMethodFactory {
28      private static final Class<?>[] NO_PARAMS = new Class[0];
29      private static final Object[] NO_ARGS = new Object[0];
30  
31      @SuppressWarnings("unchecked")
32      static <T> T createByMethod(Object template, Class<T> c) throws SecurityException, NoSuchMethodException,
33              IllegalArgumentException, IllegalAccessException, InvocationTargetException {
34          Method m;
35          m = template.getClass().getMethod("create" + c.getSimpleName(), NO_PARAMS);
36          if (m != null) {
37              Object o = m.invoke(template, NO_ARGS);
38              if (o != null && c.isAssignableFrom(o.getClass())) {
39                  return (T) o;
40  
41              }
42          }
43          return null;
44      }
45  
46      static <T> T createByConstructor(Class<T> c) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException   {
47          if(c.isInterface()) return null; //TODO medium test for abstract class
48          final Constructor<T> constr = c.getConstructor(NO_PARAMS);
49          return constr.newInstance();
50      }
51  
52  }