Example usage for java.lang Class getDeclaredMethod

List of usage examples for java.lang Class getDeclaredMethod

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.jdbcluster.JDBClusterUtil.java

/**
 * calculates method object. Iterates over all superclasses. Find a method
 * with the given method name and the given parameter types, declared on the
 * given class or one of its superclasses. Will return a public, protected,
 * package access, or private method.//  w w  w. j  a v a 2s .c o  m
 * <p>
 * Checks <code>Class.getDeclaredMethod</code>, cascading upwards to all
 * superclasses.
 * 
 * @param clazz
 *            Class of Object
 * @param methodName
 *            method name
 * @param parameterTypes
 *            parameter types of method
 * @return
 */
static public Method getDeclaredMethod(Class clazz, String methodName, Class... parameterTypes) {

    Assert.notNull(clazz, "clazz may not be null");
    Assert.hasLength(methodName, "methodName may not be null or \"\"");

    Method m = null;
    try {
        m = clazz.getDeclaredMethod(methodName, parameterTypes);
    } catch (SecurityException e) {
        throw new ConfigurationException(
                "cant get Method for method [" + methodName + "] with the specified name", e);
    } catch (NoSuchMethodException e) {
        if (clazz.getSuperclass() != null) {
            return JDBClusterUtil.getDeclaredMethod(clazz.getSuperclass(), methodName, parameterTypes);
        }
        throw new ConfigurationException(
                "cant get Method for method [" + methodName + "] with the specified name", e);
    }
    return m;
}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

/**
 * Find the invoked method on either the specified interface or any super.
 *//*w ww . ja v a2 s.co  m*/
private static Method findInterfaceMethod(Class intf, String methodName, Class[] paramTypes,
        boolean includeInherited) {
    try {
        return intf.getDeclaredMethod(methodName, paramTypes);
    } catch (NoSuchMethodException e) {
        if (includeInherited) {
            Class[] superintfs = intf.getInterfaces();
            for (int i = 0; i < superintfs.length; i++) {
                Method method = findInterfaceMethod(superintfs[i], methodName, paramTypes, true);
                if (method != null) {
                    return method;
                }
            }
        }

        return null;
    }
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

private static Method _findMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes)
        throws NoSuchMethodException {
    Method method = null;//w w  w .  j  av  a 2s  .c  o m
    try {
        method = clazz.getMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException e) {
        try {
            method = clazz.getDeclaredMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException ignore) {
        }
    }
    if (method == null) {
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz != null) {
            method = _findMethod(superClazz, methodName, parameterTypes);
        }
        if (method == null) {
            throw new NoSuchMethodException("Method: " + methodName);
        } else {
            return method;
        }
    } else {
        return method;
    }
}

From source file:com.jk.util.JKObjectUtil.java

/**
 * Call method./*from www  .  j  a v a 2s .c  o m*/
 *
 * @param obj
 *            the obj
 * @param methodName
 *            the method name
 * @param includePrivateMehtods
 *            the include private mehtods
 * @param args
 *            the args
 * @throws InvocationTargetException
 *             the invocation target exception
 */
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void callMethod(final Object obj, final String methodName, final boolean includePrivateMehtods,
        final Object... args) throws InvocationTargetException {
    final Class[] intArgsClass = initParamsClasses(args);
    try {
        Class<?> current = obj.getClass();
        Method method = null;
        while (current != Object.class) {
            try {
                method = current.getDeclaredMethod(methodName, intArgsClass);
                break;
            } catch (final NoSuchMethodException ex) {
                current = current.getSuperclass();
            }
        }
        if (method == null) {
            throw new NoSuchMethodException("Mehtod is not found in " + current);
        }
        method.setAccessible(true);
        method.invoke(obj, args);
    } catch (final InvocationTargetException e) {
        throw new InvocationTargetException(e.getCause());
    } catch (final Exception e) {
        throw new InvocationTargetException(e);
    }
}

From source file:com.cloud.hypervisor.vmware.util.VmwareHelper.java

public static String getExceptionMessage(Throwable e, boolean printStack) {
    //TODO: in vim 5.1, exceptions do not have a base exception class, MethodFault becomes a FaultInfo that we can only get
    // from individual exception through getFaultInfo, so we have to use reflection here to get MethodFault information.
    try {//w ww . j  a v a2 s  .  c  om
        Class<? extends Throwable> cls = e.getClass();
        Method mth = cls.getDeclaredMethod("getFaultInfo", (Class<?>) null);
        if (mth != null) {
            Object fault = mth.invoke(e, (Object[]) null);
            if (fault instanceof MethodFault) {
                final StringWriter writer = new StringWriter();
                writer.append("Exception: " + fault.getClass().getName() + "\n");
                writer.append("message: " + ((MethodFault) fault).getFaultMessage() + "\n");

                if (printStack) {
                    writer.append("stack: ");
                    e.printStackTrace(new PrintWriter(writer));
                }
                return writer.toString();
            }
        }
    } catch (Exception ex) {
        s_logger.info("[ignored]" + "failed toi get message for exception: " + e.getLocalizedMessage());
    }

    return ExceptionUtil.toString(e, printStack);
}

From source file:com.mawujun.utils.AnnotationUtils.java

/**
 * Get a single {@link Annotation} of {@code annotationType} from the supplied {@link Method},
 * traversing its super methods if no annotation can be found on the given method itself.
 * <p>Annotations on methods are not inherited by default, so we need to handle this explicitly.
 * @param method the method to look for annotations on
 * @param annotationType the annotation class to look for
 * @return the annotation found, or {@code null} if none found
 *///  ww w.  j a v a  2s. c  o  m
public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
    A annotation = getAnnotation(method, annotationType);
    Class<?> cl = method.getDeclaringClass();
    if (annotation == null) {
        annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces());
    }
    while (annotation == null) {
        cl = cl.getSuperclass();
        if (cl == null || cl == Object.class) {
            break;
        }
        try {
            Method equivalentMethod = cl.getDeclaredMethod(method.getName(), method.getParameterTypes());
            annotation = getAnnotation(equivalentMethod, annotationType);
        } catch (NoSuchMethodException ex) {
            // No equivalent method found
        }
        if (annotation == null) {
            annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces());
        }
    }
    return annotation;
}

From source file:com.github.valdr.thirdparty.spring.AnnotationUtils.java

/**
 * Get a single {@link java.lang.annotation.Annotation} of {@code annotationType} from the supplied {@link java.lang.reflect.Method},
 * traversing its super methods if no annotation can be found on the given method itself.
 * <p>Annotations on methods are not inherited by default, so we need to handle this explicitly.
 * @param method the method to look for annotations on
 * @param annotationType the annotation class to look for
 * @return the annotation found, or {@code null} if none found
 */// ww  w  .  java 2 s . c om
public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
    A annotation = getAnnotation(method, annotationType);
    Class<?> clazz = method.getDeclaringClass();
    if (annotation == null) {
        annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
    }
    while (annotation == null) {
        clazz = clazz.getSuperclass();
        if (clazz == null || clazz.equals(Object.class)) {
            break;
        }
        try {
            Method equivalentMethod = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
            annotation = getAnnotation(equivalentMethod, annotationType);
        } catch (NoSuchMethodException ex) {
            // No equivalent method found
        }
        if (annotation == null) {
            annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
        }
    }
    return annotation;
}

From source file:gov.llnl.lc.smt.command.file.SmtFile.java

/**
 * if the provided name maps to the provided type, return true,
 * otherwise return false;/*w  w  w  .  j  ava 2 s  .c o  m*/
 *
 * @see     describe related java objects
 *
 * @param fileName
 * @return
 ***********************************************************/
public static boolean isFileType(String fileName, SmtProperty fileType) {
    if ((fileName == null) || !(SmtProperty.SMT_FILE_TYPES.contains(fileType)))
        return false;

    logger.severe("is file: " + fileName + " of type: " + fileType.getPropertyName());

    String fn = convertSpecialFileName(fileName);

    // parameter types for all read file (just a filename
    Class[] partypes = new Class[] { String.class };

    // Arguments to be passed into method
    Object[] arglist = new String[] { fn };

    String className = fileType.getPropertyName();
    String methodName = fileType.getName();

    // attempt to open this file, using this class
    Class<?> smtClass = null;
    try {
        smtClass = Class.forName(className);
        Method m = smtClass.getDeclaredMethod(methodName, partypes);
        Object o = m.invoke(null, arglist);

        // previous should throw an exception if not the correct type, but...
        // final sanity check

        String type = o.getClass().getCanonicalName();
        if (className.equals(type))
            return true;

        // if I am here, then the read method didn't throw an exception, but also didn't match class names????
        return false;
    } catch (Exception e) {
        logger.info("File NOT: " + className);
    }
    return false;
}

From source file:gov.llnl.lc.smt.command.file.SmtFile.java

public static Object getFileObject(String fileName) {
    String fn = convertSpecialFileName(fileName);

    //parameter types for all read file (just a filename)
    Class[] partypes = new Class[] { String.class };

    //Arguments to be passed into method
    Object[] arglist = new String[] { fn };

    // sort the various types based on the the priority (or probability)
    TreeSet<SmtProperty> ft = SmtProperty.sortPropertySet(SmtProperty.SMT_FILE_TYPES);

    for (SmtProperty s : ft) {
        String className = s.getPropertyName();
        String methodRead = s.getName();

        // attempt to open this file, using this class
        Class<?> smtClass = null;
        try {/*ww  w .ja  va2  s.com*/
            smtClass = Class.forName(className);

            Method r = smtClass.getDeclaredMethod(methodRead, partypes);
            Object o = r.invoke(null, arglist);

            // if I am here, then it didn't throw an exception, but did I get anything?
            if (o != null)
                return o;
        } catch (Exception e) {
            logger.severe("File NOT: " + className);
        }
    }
    return "Could not obtain an object from the file File";
}

From source file:com.just.agentweb.AgentWebUtils.java

static Method isExistMethod(Object o, String methodName, Class... clazzs) {

    if (null == o) {
        return null;
    }//from w  w w  .java2s .  c o  m
    try {
        Class clazz = o.getClass();
        Method mMethod = clazz.getDeclaredMethod(methodName, clazzs);
        mMethod.setAccessible(true);
        return mMethod;
    } catch (Throwable ignore) {
        if (LogUtils.isDebug()) {
            ignore.printStackTrace();
        }
    }
    return null;

}