invoke Method If Exists - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

invoke Method If Exists

Demo Code


//package com.java2s;
import java.lang.reflect.Method;

public class Main {
    public static void invokeMethodIfExists(String methodName,
            Object target, Class<?>[] paramTypes, Object... params) {
        Class<?> c = target.getClass();
        try {// w ww  . ja va2s. c o m
            Method method = c.getMethod(methodName, paramTypes);
            method.invoke(target, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void invokeMethodIfExists(String methodName,
            Object target, Object[] params) {
        Class<?> c = target.getClass();
        Method[] methods = c.getMethods();
        Method matchedMethod = null;
        for (Method m : methods) {
            if (!m.getName().equals(methodName)) {
                continue;
            }

            Class<?>[] types = m.getParameterTypes();

            if (types.length != params.length) {
                continue;
            }

            boolean matched = true;
            final int len = params.length;
            for (int i = 0; i < len; i++) {
                if (!types[i].isInstance(params[i])) {
                    matched = false;
                    break;
                }
            }
            if (matched) {
                matchedMethod = m;
                break;
            }
        }
        if (matchedMethod != null) {
            try {
                matchedMethod.invoke(target, params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Related Tutorials