invoke Adaptive Static Method - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

invoke Adaptive Static Method

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

import android.util.Log;

public class Main {
    private static final String TAG = "loader";

    public static Object invokeAdaptiveStaticMethod(Class clzz,
            String methodname, Object[] args) {
        if (methodname == null)
            return null;
        Method method = null;/*from www .ja v  a 2  s  . co m*/
        try {
            Method[] methods = clzz.getDeclaredMethods();
            int len = methods.length;
            for (int i = 0; i < len; i++) {
                if (methodname.equals(methods[i].getName())) {
                    method = methods[i];
                    break;
                }
            }
            Object[] objs = null;

            int paramLen = method.getParameterTypes().length;
            if (paramLen == args.length) {
                objs = args;
            } else {
                objs = new Object[paramLen];
                objs[objs.length - 1] = 0;
                for (int i = 0; i < args.length; i++) {
                    objs[i] = args[i];
                }
            }
            method.setAccessible(true);
            Object res = method.invoke(null, objs);

            if (res != null)
                return res;
        } catch (Exception e1) {

            Log.e(TAG, "", e1);
            return null;
        }
        return null;
    }
}

Related Tutorials