invoke a method on a class with parameters. - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

invoke a method on a class with parameters.

Demo Code

/**//from   w  ww  .j a va  2 s  . co m
 * utilities to access and set fields in objects via reflection
 * @author Matthew
 * Copyright (c) 2013 Visible Automation LLC.  All Rights Reserved.
 */
//package com.java2s;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    /**
     * invoke a method on a class with parameters.
     * @param object
     * @param cls
     * @param methodName
     * @param args
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static boolean execMethodBoolean(Object object, Class cls,
            String methodName, Object... args)
            throws NoSuchMethodException, IllegalAccessException,
            InvocationTargetException {
        Class[] parameterTypes = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            parameterTypes[i] = args.getClass();
        }
        Method method = cls.getDeclaredMethod(methodName, parameterTypes);
        Boolean b = (Boolean) method.invoke(object, args);
        return b.booleanValue();
    }
}

Related Tutorials