Here you can find the source of invokeMethod(Object target, Class> clazz, String methodName, Class[] types, Object[] args)
Parameter | Description |
---|---|
target | the target |
clazz | the class |
methodName | the method name |
types | the types |
args | the args |
private static Object invokeMethod(Object target, Class<?> clazz, String methodName, Class[] types, Object[] args)
//package com.java2s; /*/*from ww w .j av a 2s . c o m*/ * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ import java.lang.reflect.Method; public class Main { /** * Invoke method. * * @param target the target * @param clazz the class * @param methodName the method name * @param types the types * @param args the args * @return method's return value */ private static Object invokeMethod(Object target, Class<?> clazz, String methodName, Class[] types, Object[] args) { final Method m = findMethod(clazz, methodName, types); try { return m.invoke(target, args); } catch (Exception e) { throw new RuntimeException(e); } } /** * Find method. * * @param clazz the class * @param methodName the method name * @param types the types * @return method's return value */ private static Method findMethod(Class<?> clazz, String methodName, Class[] types) { if (clazz == null) throw new IllegalArgumentException("Null class"); if (methodName == null) throw new IllegalArgumentException("Null method name"); try { Class<?> current = clazz; while (current != null) { try { final Method m = current.getDeclaredMethod(methodName, types); m.setAccessible(true); return m; } catch (NoSuchMethodException ignored) { } current = current.getSuperclass(); } } catch (Throwable t) { throw new RuntimeException(t); } throw new IllegalStateException("Couldn't find method: " + clazz.getName() + " / " + methodName); } }