Call every method on object that begins with "get" or "is" - Java Reflection

Java examples for Reflection:Method

Description

Call every method on object that begins with "get" or "is"

Demo Code


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

import java.util.LinkedHashMap;
import java.util.Map;

public class Main {


    /**/* w ww . j a v  a2 s . c om*/
     * Call every method on object that begins with "get" or "is"
     *
     * @return map of parameter to value.
     */
    public static Map<String, String> callEveryBeanMethodOnObject(Object o) {
        Map<String, String> data = new LinkedHashMap<String, String>();
        for (Method m : o.getClass().getMethods()) {
            final String methodName = m.getName();
            if ((methodName.startsWith("get") || methodName
                    .startsWith("is"))
                    && m.getParameterTypes().length == 0
                    && methodName != "getClass") {
                try {
                    Object value = m.invoke(o, (Object[]) null);
                    if (value instanceof byte[]) { // byte arrays are "special"
                        System.err.println("\n\nI was called\n\n");
                        data.put(methodName, "byte["
                                + ((byte[]) value).length + "]"); // cast to String
                        continue; // Skip for now. Is this causing gnome-terminal display issues?
                    }//else
                    data.put(methodName, "" + value); // cast to String
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return data;
    }
}

Related Tutorials