call Method on object via reflection - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

call Method on object via reflection

Demo Code

/**//from w  w w.  j a v  a  2 s. c  o m
 * (c) Winterwell Associates Ltd, used under MIT License. This file is background IP.
 */
//package com.java2s;

import java.lang.reflect.Method;

public class Main {
    public static void callMethod(Object obj, String method,
            Object... params) {
        Method[] ms = obj.getClass().getMethods();
        for (Method m : ms) {
            if (!m.getName().equals(method))
                continue;
            // TODO check type args
            Class<?>[] types = m.getParameterTypes();
            if (params.length != types.length)
                continue;
            for (int i = 0; i < params.length; i++) {

            }
            // call
            try {
                m.invoke(obj, params);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        throw new RuntimeException(obj + "." + method + "(" + params.length
                + ")");
    }

    /**
     * Lenient equals: null = ""
     * @param a
     * @param b
     * @return true if a=b
     */
    public static boolean equals(String a, String b) {
        if (a == null || a.length() == 0)
            return b == null || b.length() == 0;
        return a.equals(b);
    }
}

Related Tutorials