View Javadoc
1   /*
2    * #%L
3    * JRst :: Site util
4    * %%
5    * Copyright (C) 2006 - 2011 CodeLutin
6    * %%
7    * This program is free software: you can redistribute it and/or modify
8    * it under the terms of the GNU Lesser General Public License as 
9    * published by the Free Software Foundation, either version 3 of the 
10   * License, or (at your option) any later version.
11   * 
12   * This program is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   * GNU General Lesser Public License for more details.
16   * 
17   * You should have received a copy of the GNU General Lesser Public 
18   * License along with this program.  If not, see
19   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
20   * #L%
21   */
22  package org.nuiton.jrst;
23  
24  import java.lang.reflect.Field;
25  import java.lang.reflect.Method;
26  
27  /**
28   * Some usefull methods to obtains none accessible fields and method from
29   * some classes.
30   *
31   * @author tchemit <chemit@codelutin.com>
32   * @since 1.0.6
33   */
34  public class ReflectUtil {
35  
36      public static Method getMethod(Class<?> klass, String methodName, Class<?>[] paramTypes) {
37          try {
38              Method declaredMethod = klass.getDeclaredMethod(methodName, paramTypes);
39              declaredMethod.setAccessible(true);
40              return declaredMethod;
41          } catch (Exception e) {
42              throw new IllegalStateException("Could not get method [" + methodName + "] from parent class :(... ", e);
43          }
44  
45      }
46  
47      public static Field getField(Class<?> klass, String fieldName) {
48          try {
49              Field declaredField = klass.getDeclaredField(fieldName);
50              declaredField.setAccessible(true);
51              return declaredField;
52          } catch (Exception e) {
53              throw new IllegalStateException("Could not get field [" + fieldName + "] from parent class :(... ", e);
54          }
55  
56      }
57  
58      public static <O> O invokeMethod(Method m, Object o, Object... params) {
59          try {
60              O result = (O) m.invoke(o, params);
61              return result;
62          } catch (Exception e) {
63              throw new IllegalStateException("Could not invoke method [" + m.getName() + "] from parent class :(... ", e);
64          }
65  
66      }
67  }