Here you can find the source of invokeMethod(Object target, String name, Class>... parameterTypes)
Parameter | Description |
---|---|
target | the target object |
name | method name |
parameterTypes | method's parameters types. |
public static <T> T invokeMethod(Object target, String name, Class<?>... parameterTypes)
//package com.java2s; /**//from w w w .j a va 2s . c o m * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.Method; public class Main { /** * Safely invoke a method with the given signature (name + parameter types) on the given target object. * * @param target * the target object * @param name * method name * @param parameterTypes * method's parameters types. * @return * the value returned by the method invocation. */ public static <T> T invokeMethod(Object target, String name, Class<?>... parameterTypes) { Method method = findMethod(target.getClass(), name, parameterTypes); try { return (T) method.invoke(target, parameterTypes); } catch (Exception e) { return null; } } /** * Safely search for a method with a given signature (name + parameter types) on a given class. * * @param clazz * the target class * @param name * method name * @param parameterTypes * method's parameters types. * @return * the method corresponding to the given signature, null if such a method doesn't exist. */ public static Method findMethod(Class<?> clazz, String name, Class<?>... parameterTypes) { try { Method method = clazz.getMethod(name, parameterTypes); return method; } catch (Exception e) { return null; } } }