Here you can find the source of invokeMethod(Object o, String methodName, Object... args)
Parameter | Description |
---|---|
o | The object that contains the field |
methodName | The name of the field |
args | The arguments. |
public static Object invokeMethod(Object o, String methodName, Object... args) throws Throwable
//package com.java2s; /*//from ww w .ja va2 s. co m * * Copyright 2016,2017 DTCC, Fujitsu Australia Software Technology, IBM - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class Main { /** * Invokes method on object. * Used to access private methods. * * @param o The object that contains the field * @param methodName The name of the field * @param args The arguments. * @return Result of method. */ public static Object invokeMethod(Object o, String methodName, Object... args) throws Throwable { Method[] methods = o.getClass().getDeclaredMethods(); List<Method> reduce = new ArrayList<>(Arrays.asList(methods)); for (Iterator<Method> i = reduce.iterator(); i.hasNext();) { Method m = i.next(); if (!methodName.equals(m.getName())) { i.remove(); continue; } Class<?>[] parameterTypes = m.getParameterTypes(); if (parameterTypes.length != args.length) { i.remove(); continue; } } if (reduce.isEmpty()) { throw new RuntimeException(String.format("TEST ISSUE Could not find method %s on %s with %d arguments.", methodName, o.getClass().getName(), args.length)); } if (reduce.size() > 1) { throw new RuntimeException( String.format("TEST ISSUE Could not find unique method %s on %s. Found with %d matches.", methodName, o.getClass().getName(), reduce.size())); } Method method = reduce.iterator().next(); method.setAccessible(true); try { return method.invoke(o, args); } catch (IllegalAccessException e) { throw e; } catch (InvocationTargetException e) { throw e.getTargetException(); } } }