Example usage for java.lang Class getMethod

List of usage examples for java.lang Class getMethod

Introduction

In this page you can find the example usage for java.lang Class getMethod.

Prototype

@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

Usage

From source file:com.jkoolcloud.tnt4j.streams.matchers.StringMatcher.java

private static Method findMatchingMethodAndConvertArgs(Object methodName, String[] arguments,
        Object[] convertedArguments, Method[] methods) {
    for (Method method : methods) {
        if (method.getName().equals(methodName) && method.getParameterTypes().length == arguments.length + 1) {
            boolean methodMatch = true;
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 1; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];
                if (CharSequence.class.isAssignableFrom(parameterType)) {
                    convertedArguments[i - 1] = arguments[i - 1];
                } else {
                    try {
                        if (parameterType.isPrimitive()) {
                            parameterType = ClassUtils.primitiveToWrapper(parameterType);
                        }//  w  w  w. jav  a 2s.  co m
                        Method converterMethod = parameterType.getMethod("valueOf", String.class);
                        convertedArguments[i - 1] = converterMethod.invoke(null, arguments[i - 1]);
                    } catch (Exception e) {
                        methodMatch = false;
                        break;
                    }
                }
            }

            if (methodMatch) {
                return method;
            }
        }
    }
    return null;
}

From source file:com.austin.base.commons.util.ReflectUtil.java

/**
 * @param owner //from w w  w  .  ja  v a  2s.  c o m
 * @param methodName ??
 * @param args ?
 * @return 
 */
public static Object invokeMethod(Object owner, String methodName, Object[] args)

{

    Class ownerClass = owner.getClass();

    Class[] argsClass = new Class[args.length];

    for (int i = 0, j = args.length; i > j; i++) {
        argsClass[i] = args[i].getClass();
    }

    try {
        Method method = ownerClass.getMethod(methodName, argsClass);

        return method.invoke(owner, args);
    } catch (Exception ex) {
        log.error(ex);
        return null;
    }

}

From source file:com.aw.support.reflection.MethodInvoker.java

public static Object invoke(Object target, String methodName, Object[] parameters, Class[] parameterTypes) {
    Object result = null;/*from   ww  w.  j a  v a  2 s  .  c  o  m*/
    try {
        Class cls = target.getClass();
        Class[] paramTypes = parameterTypes;
        for (int i = 0; i < paramTypes.length; i++) {
            if (parameterTypes[i] == null) {
                paramTypes[i] = parameters[i].getClass();
            }
        }
        Method method = cls.getMethod(methodName, paramTypes);
        method.setAccessible(true);
        result = method.invoke(target, parameters);
    } catch (Throwable e) {
        if (!(e instanceof AWException)) {
            if (e.getCause() instanceof AWException) {
                throw ((AWException) e.getCause());
            }
            e.printStackTrace();
            throw new AWSystemException("Problems calling the method:" + methodName, e);
        } else {
            throw (AWException) e;
        }
    }
    return result;
}

From source file:com.austin.base.commons.util.ReflectUtil.java

/**
 * @param className ??// w  w w  .ja v a2  s  .co  m
 * @param methodName ?17??17
 * @param args ?
 * @return 
 */
public static Object invokeStaticMethod(String className, String methodName, Object[] args) {
    try {
        Class ownerClass = Class.forName(className);

        Class[] argsClass = new Class[args.length];

        for (int i = 0, j = args.length; i > j; i++) {
            argsClass[i] = args[i].getClass();
        }

        Method method = ownerClass.getMethod(methodName, argsClass);

        return method.invoke(null, args);
    } catch (Exception ex) {
        log.error(ex);
        return null;

    }
}

From source file:net.servicefixture.util.ReflectionUtils.java

/**
 * Returns true if it is an enumeration type.
 * //  w  ww .jav  a 2 s  .c  o  m
 * @param type
 * @return
 */
public static boolean isEnumarationPatternClass(Class type) {
    try {
        //JDK1.4 Enumeration Pattern
        Constructor[] constructors = type.getConstructors();
        for (int i = 0; i < constructors.length; i++) {
            if (Modifier.isPublic(constructors[i].getModifiers())) {
                return false;
            }
        }
        type.getMethod("fromString", new Class[] { String.class });
        return true;
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    }
    return false;
}

From source file:Main.java

public static Object xmlToBean(Node beanNode) throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, NoSuchMethodException, InvocationTargetException {
    String className = beanNode.getNodeName();
    System.out.println(className);
    Class clazz = Class.forName(className);
    Object bean = clazz.newInstance();
    NodeList fieldNodeList = beanNode.getChildNodes();
    for (int i = 0; i < fieldNodeList.getLength(); i++) {
        Node fieldNode = fieldNodeList.item(i);
        if (fieldNode.getNodeType() == Node.ELEMENT_NODE) {
            String fieldName = fieldNode.getNodeName();
            if (!fieldName.contains(".")) {
                String getName = analyzeMethodName(fieldName, "get");
                String setName = analyzeMethodName(fieldName, "set");
                System.out.println(setName);
                clazz.getMethod(setName, clazz.getMethod(getName).getReturnType()).invoke(bean,
                        fieldNode.getTextContent());
            }//from w ww  .j  a  v a  2 s.com
        }
    }
    System.out.println(bean);
    return bean;
}

From source file:com.aurel.track.persist.ReflectionHelper.java

/**
 * This method sets to null all occurrences of oldOID
 * going through all related tables in the database.
 * @param oldOID object identifier to be replaced 
 *//*from   w  w  w  .  j  a  v  a  2s  .  c o  m*/
public static void setToNull(Class[] peerClasses, String[] fields, Integer oldOID) {
    Criteria selectCriteria = new Criteria();
    Criteria updateCriteria = new Criteria();
    for (int i = 0; i < peerClasses.length; ++i) {
        Class peerClass = peerClasses[i];
        String field = fields[i];
        selectCriteria.clear();
        updateCriteria.clear();
        selectCriteria.add(field, oldOID, Criteria.EQUAL);
        updateCriteria.add(field, (Object) null, Criteria.ISNULL);
        try {
            Class partypes[] = new Class[2];
            partypes[0] = Criteria.class;
            partypes[1] = Criteria.class;
            Method meth = peerClass.getMethod("doUpdate", partypes);

            Object arglist[] = new Object[2];
            arglist[0] = selectCriteria;
            arglist[1] = updateCriteria;
            meth.invoke(peerClass, arglist);
        } catch (Exception e) {
            LOGGER.error("Exception when trying to set " + "oldOID " + oldOID + " to null " + " for class "
                    + peerClass.toString() + " and field " + field + ": " + e.getMessage(), e);
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:net.servicefixture.converter.ObjectConverter.java

/**
 * Converts types that are supported by <code>ConvertUtils</code>.
 * /*from  w  w  w. j a  va 2s.  c o  m*/
 * @param data
 * @param destType
 * @return
 */
public static Object specialConvert(String data, Class destType) {
    try {
        //If it is enumeration class.
        if (ReflectionUtils.isEnumarationPatternClass(destType)) {
            try {
                Field field = destType.getField(data);
                return field.get(null);
            } catch (NoSuchFieldException e) {
                //No such field, meaning the variable name and the data
                //doesn't match, call fromString method.
                return destType.getMethod("fromString", new Class[] { String.class }).invoke(null,
                        new Object[] { data });
            }
        }
        //JDK5.0 enum type
        if (destType.isEnum()) {
            return destType.getMethod("valueOf", String.class).invoke(null, data);
        }
    } catch (Exception ignoreIt) {
        ignoreIt.printStackTrace();
    }

    throw new ServiceFixtureException("Unable to convert data:" + data + " to class:" + destType.getName());
}

From source file:SocketFetcher.java

/**
 * Return a socket factory of the specified class.
 *//*from www  .ja  v a2 s .  co  m*/
private static SocketFactory getSocketFactory(String sfClass) throws ClassNotFoundException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (sfClass == null || sfClass.length() == 0)
        return null;

    // dynamically load the class

    ClassLoader cl = getContextClassLoader();
    Class clsSockFact = null;
    if (cl != null) {
        try {
            clsSockFact = cl.loadClass(sfClass);
        } catch (ClassNotFoundException cex) {
        }
    }
    if (clsSockFact == null)
        clsSockFact = Class.forName(sfClass);
    // get & invoke the getDefault() method
    Method mthGetDefault = clsSockFact.getMethod("getDefault", new Class[] {});
    SocketFactory sf = (SocketFactory) mthGetDefault.invoke(new Object(), new Object[] {});
    return sf;
}

From source file:com.buaa.cfs.utils.ReflectionUtils.java

/**
 * This code is to support backward compatibility and break the compile time dependency of core on mapred. This
 * should be made deprecated along with the mapred package HADOOP-1230. Should be removed when mapred package is
 * removed./*ww  w  .  j  ava  2 s  .  c o  m*/
 */
private static void setJobConf(Object theObject, Configuration conf) {
    //If JobConf and JobConfigurable are in classpath, AND
    //theObject is of type JobConfigurable AND
    //conf is of type JobConf then
    //invoke configure on theObject
    try {
        Class<?> jobConfClass = conf.getClassByNameOrNull("org.apache.hadoop.mapred.JobConf");
        if (jobConfClass == null) {
            return;
        }

        Class<?> jobConfigurableClass = conf.getClassByNameOrNull("org.apache.hadoop.mapred.JobConfigurable");
        if (jobConfigurableClass == null) {
            return;
        }
        if (jobConfClass.isAssignableFrom(conf.getClass())
                && jobConfigurableClass.isAssignableFrom(theObject.getClass())) {
            Method configureMethod = jobConfigurableClass.getMethod("configure", jobConfClass);
            configureMethod.invoke(theObject, conf);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error in configuring object", e);
    }
}