Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.lang.reflect.*;

public class Main {
    public static <T extends Object> void callMethod(T receiver, String methodName, Object... args)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
            InstantiationException {
        callMethodCast(receiver, null, methodName, args);
    }

    public static <T extends Object, Result> Result callMethodCast(T receiver, Class<Result> resultClass,
            String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException,
            InvocationTargetException, InstantiationException {
        if (receiver == null || methodName == null) {
            return null;
        }
        Class<?> cls = receiver.getClass();
        Method toInvoke = null;
        do {
            Method[] methods = cls.getDeclaredMethods();
            methodLoop: for (Method method : methods) {
                if (!methodName.equals(method.getName())) {
                    continue;
                }
                Class<?>[] paramTypes = method.getParameterTypes();
                if (args == null && paramTypes == null) {
                    toInvoke = method;
                    break;
                } else if (args == null || paramTypes == null || paramTypes.length != args.length) {
                    continue;
                }

                for (int i = 0; i < args.length; ++i) {
                    if (!paramTypes[i].isAssignableFrom(args[i].getClass())) {
                        continue methodLoop;
                    }
                }
                toInvoke = method;
            }
        } while (toInvoke == null && (cls = cls.getSuperclass()) != null);
        Result t;
        if (toInvoke != null) {
            boolean accessible = toInvoke.isAccessible();
            toInvoke.setAccessible(true);
            if (resultClass != null) {
                t = resultClass.cast(toInvoke.invoke(receiver, args));
            } else {
                toInvoke.invoke(receiver, args);
                t = null;
            }
            toInvoke.setAccessible(accessible);
            return t;
        } else {
            throw new NoSuchMethodException("Method " + methodName + " not found");
        }
    }
}