Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Main {
    /**
     *  find the Appropriate method
     *  @throws NoSuchMethodException if not find
     */
    public static Method getAppropriateMethod(Class<?> clazz, String methodName, Class<?>... paramTypes)
            throws NoSuchMethodException {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException e) {
            final List<Method> ms = getMethods(clazz, methodName);
            final int size = ms.size();
            switch (size) {
            case 0:
                throw new NoSuchMethodException(
                        "can't find the method , methodName = " + methodName + " ,classname = " + clazz.getName());
            case 1:
                return ms.get(0);
            default:
                throw new NoSuchMethodException("You should not have multi methods with the same name of "
                        + methodName + "in class " + clazz.getName() + "( that means don't burden method )!");
            }
        }
    }

    public static List<Method> getMethods(Class<?> clazz, String methodName) {
        List<Method> list = new ArrayList<>();
        Method[] ms = clazz.getMethods();
        if (ms != null) {
            for (int size = ms.length, i = size - 1; i >= 0; i--) {
                if (ms[i].getName().equals(methodName)) {
                    list.add(ms[i]);
                }
            }
        }
        return list;
    }
}