Java Reflection Method Get from Object getMethod(Class type, String name, Object[] args)

Here you can find the source of getMethod(Class type, String name, Object[] args)

Description

get Method

License

Apache License

Declaration

public static Method getMethod(Class<?> type, String name, Object[] args) 

Method Source Code


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

import java.lang.reflect.*;
import java.util.Arrays;

public class Main {
    public static Method getMethod(Class<?> type, String name, Object[] args) {
        return selectMethod(getMethods(type, name), args);
    }/*from   www.j  av a 2 s .c  om*/

    public static Method selectMethod(Method[] methods, Object[] args) {
        for (Method m : methods) {
            if (instanceOfs(m.getParameterTypes(), args))
                return m;
        }

        return null;
    }

    public static Method[] getMethods(Class<?> type, String name) {
        return Arrays.stream(type.getMethods()).filter(m -> name.equals(m.getName())).toArray(Method[]::new);
    }

    public static boolean instanceOfs(Class<?>[] classes, Object[] objs) {
        if (objs.length != classes.length)
            return false;

        for (int i = 0; i < objs.length; i++) {
            if (objs[i] != null && !asBoxedClass(classes[i]).isInstance(objs[i]))
                return false;
        }

        return true;
    }

    public static Class<?> asBoxedClass(Class<?> c) {
        if (!c.isPrimitive())
            return c;
        else if (c == Boolean.TYPE)
            return Boolean.class;
        else if (c == Byte.TYPE)
            return Byte.class;
        else if (c == Character.TYPE)
            return Character.class;
        else if (c == Short.TYPE)
            return Short.class;
        else if (c == Integer.TYPE)
            return Integer.class;
        else if (c == Long.TYPE)
            return Long.class;
        else if (c == Float.TYPE)
            return Float.class;
        else if (c == Double.TYPE)
            return Double.class;
        else
            throw new RuntimeException(new ClassNotFoundException());
    }
}

Related

  1. getMethod(Class type, String name, Class... parameterTypes)
  2. getMethod(Class cls, String method, Object[] params)
  3. getMethod(Class clz, String methodName, Object... params)
  4. getMethod(Class klass, String methodName, Object... params)
  5. getMethod(Class objectType, String methodName, Class... parameterTypes)
  6. getMethod(final Class clazz, final String methodName, final Class[] parTypes, final Object[] parameters)
  7. getMethod(final Object object, final String methodName, final Class... parameterClass)
  8. getMethod(final Object object, final String methodName, final Object... arguments)
  9. getMethod(final Object object, final String methodName, final Object... arguments)