Use reflection to invoke a static method for a class object and method name - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

Use reflection to invoke a static method for a class object and method name

Demo Code

/*/*  w  w  w. j  a  va  2  s. c  om*/
 * ReflectionUtils.java Copyright (C) 2013 Char Software Inc., DBA Localytics. This code is provided under the Localytics
 * Modified BSD License. A copy of this license has been distributed in a file called LICENSE with this source code. Please visit
 * www.localytics.com for more information.
 */
//package com.java2s;
import java.lang.reflect.InvocationTargetException;

public class Main {
    /**
     * Use reflection to invoke a static method for a class object and method name
     *
     * @param <T> Type that the method should return
     * @param target Object instance on which to invoke {@code methodName}. Cannot be null.
     * @param methodName Name of the method to invoke. Cannot be null.
     * @param types explicit types for the objects. This is useful if the types are primitives, rather than objects.
     * @param args arguments for the method. May be null if the method takes no arguments.
     * @return The result of invoking the named method on the given class for the args
     * @throws RuntimeException if the class or method doesn't exist
     */
    @SuppressWarnings("unchecked")
    public static <T> T tryInvokeInstance(final Object target,
            final String methodName, final Class<?>[] types,
            final Object[] args) {
        return (T) helper(target, null, null, methodName, types, args);
    }

    @SuppressWarnings("unchecked")
    private static <T> T helper(final Object target,
            final Class<?> classObject, final String className,
            final String methodName, final Class<?>[] argTypes,
            final Object[] args) {
        try {
            Class<?> cls;
            if (classObject != null) {
                cls = classObject;
            } else if (target != null) {
                cls = target.getClass();
            } else {
                cls = Class.forName(className);
            }

            return (T) cls.getMethod(methodName, argTypes).invoke(target,
                    args);
        } catch (final NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (final InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (final ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials