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.aw.support.reflection.MethodInvoker.java

/**
 * @param target/*from www  .  j ava  2  s  . c  o  m*/
 * @param methodName
 * @param parameter
 * @return
 * @throws Throwable
 */
public static Object invoke(Object target, String methodName, Object parameter) throws Throwable {
    Object result = null;
    try {
        Class cls = target.getClass();
        Class[] paramTypes = new Class[] { Object.class };
        Method method = cls.getMethod(methodName, paramTypes);
        result = method.invoke(target, new Object[] { parameter });
    } catch (Throwable e) {
        Throwable cause = e.getCause();
        if ((cause instanceof FlowBreakSilentlyException) || (cause instanceof AWException)
                || (cause instanceof DataIntegrityViolationException)) {
            throw cause;
        }
        e.printStackTrace();
        throw e;

    }
    return result;
}

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

/**
 * @param target/*  www .  jav  a  2 s . co  m*/
 * @param methodName
 * @param parameter
 * @return
 * @throws Throwable
 */
public static Object invoke(Object target, String methodName, Object parameter, Class parameterType)
        throws Throwable {
    Object result = null;
    try {
        Class cls = target.getClass();
        Class[] paramTypes = new Class[] { parameterType };
        Method method = cls.getMethod(methodName, paramTypes);
        result = method.invoke(target, new Object[] { parameter });
    } catch (Throwable e) {
        Throwable cause = e.getCause();
        if ((cause instanceof FlowBreakSilentlyException) || (cause instanceof AWException)
                || (cause instanceof DataIntegrityViolationException)) {
            throw cause;
        }
        e.printStackTrace();
        throw e;
    }
    return result;
}

From source file:net.sensemaker.snappy.SnappyUtil.java

public static void setBooleanProperty(String property, Object target, boolean value) {
    Class clazz = target.getClass();
    property = Character.toUpperCase(property.charAt(0)) + property.substring(1);
    Method method = null;/*from   w  w  w  .ja  v a  2s  .c  o m*/
    String methodName = "set" + property;
    try {
        method = clazz.getMethod(methodName, Boolean.class);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Method " + methodName + " not found in " + clazz.getName());
    }
    try {
        method.invoke(target, new Object[] { value });
    } catch (Exception e) {
        throw new RuntimeException("Error setting property " + property + " in " + clazz.getName(), e);
    }
}

From source file:ca.sqlpower.testutil.TestUtils.java

/**
 * Returns the set of property names which have both a getter and a setter
 * method and are annotated to be persisted through the {@link SPPersister}
 * classes.//  w  ww.j a  v a2  s . c o  m
 * 
 * @param objectUnderTest
 *            The object that contains the persistable properties we want to
 *            find.
 * @param includeTransient
 *            If true the properties marked as transient will also be
 *            included. If false only the properties that are persisted and
 *            not transient are returned.
 * @param includeConstructorMutators
 *            If true the properties that have getters but can only be set
 *            through a constructor due to being final will be included. If
 *            false the persisted properties provided must have a setter.
 */
public static Set<String> findPersistableBeanProperties(SPObject objectUnderTest, boolean includeTransient,
        boolean includeConstructorMutators) throws Exception {
    Set<String> getters = new HashSet<String>();
    Set<String> setters = new HashSet<String>();
    for (Method m : objectUnderTest.getClass().getMethods()) {
        if (m.getName().equals("getClass"))
            continue;

        //skip non-public methods as they are not visible for persisting anyways.
        if (!Modifier.isPublic(m.getModifiers()))
            continue;
        //skip static methods
        if (Modifier.isStatic(m.getModifiers()))
            continue;

        if (m.getName().startsWith("get") || m.getName().startsWith("is")) {
            Class<?> parentClass = objectUnderTest.getClass();
            boolean accessor = false;
            boolean ignored = false;
            boolean isTransient = false;
            parentClass.getMethod(m.getName(), m.getParameterTypes());//test
            while (parentClass != null) {
                Method parentMethod;
                try {
                    parentMethod = parentClass.getMethod(m.getName(), m.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    parentClass = parentClass.getSuperclass();
                    continue;
                }
                if (parentMethod.getAnnotation(Accessor.class) != null) {
                    accessor = true;
                    if (parentMethod.getAnnotation(Transient.class) != null) {
                        isTransient = true;
                    }
                    break;
                } else if (parentMethod.getAnnotation(NonProperty.class) != null
                        || parentMethod.getAnnotation(NonBound.class) != null) {
                    ignored = true;
                    break;
                }
                parentClass = parentClass.getSuperclass();
            }
            if (accessor) {
                if (includeTransient || !isTransient) {
                    if (m.getName().startsWith("get")) {
                        getters.add(m.getName().substring(3));
                    } else if (m.getName().startsWith("is")) {
                        getters.add(m.getName().substring(2));
                    }
                }
            } else if (ignored) {
                //ignored so skip
            } else {
                fail("The method " + m.getName() + " of " + objectUnderTest.toString()
                        + " is a getter that is not annotated "
                        + "to be an accessor or transient. The exiting annotations are "
                        + Arrays.toString(m.getAnnotations()));
            }
        } else if (m.getName().startsWith("set")) {
            if (m.getAnnotation(Mutator.class) != null) {
                if ((includeTransient || m.getAnnotation(Transient.class) == null)
                        && (includeConstructorMutators
                                || !m.getAnnotation(Mutator.class).constructorMutator())) {
                    setters.add(m.getName().substring(3));
                }
            } else if (m.getAnnotation(NonProperty.class) != null || m.getAnnotation(NonBound.class) != null) {
                //ignored so skip and pass
            } else {
                fail("The method " + m.getName() + " is a setter that is not annotated "
                        + "to be a mutator or transient.");
            }
        }
    }

    Set<String> beanNames = new HashSet<String>();
    for (String beanName : getters) {
        if (setters.contains(beanName)) {
            String firstLetter = new String(new char[] { beanName.charAt(0) });
            beanNames.add(beanName.replaceFirst(firstLetter, firstLetter.toLowerCase()));
        }
    }
    return beanNames;
}

From source file:fit.Fixture.java

public static Object callParseMethod(Class<?> type, String s) throws Exception {
    Method parseMethod = type.getMethod("parse", String.class);
    return parseMethod.invoke(null, s);
}

From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java

/***
 * Set an Enumerator value./*from ww w . j a  v a  2 s . c  om*/
 * The Enumerator class must implement the IProperties interface
 * @param en The Enumerator class
 * @param iKey
 * @param value
 * @throws ConfigurationException 
 * @throws PushNotInitializedException 
 * @throws PushSwitchException 
 * @throws Exception
 */
public static void setByKey(Class en, String iKey, Object value) throws ConfigurationException {
    Object enumValue = findByKey(en, iKey);
    try {
        en.getMethod("setValue", Object.class).invoke(enumValue, value);
    } catch (Exception e) {
        if (e.getCause() instanceof IllegalStateException)
            throw new IllegalStateException(e.getCause());
        if (e.getCause() instanceof PushSwitchException)
            throw (PushSwitchException) e.getCause();
        if (e.getCause() instanceof PushNotInitializedException)
            throw (PushNotInitializedException) e.getCause();
        if (e.getCause() instanceof PushInvalidApiKeyException)
            throw (PushInvalidApiKeyException) e.getCause();
        throw new ConfigurationException("Invalid key (" + iKey + ") or value (" + value + ")", e);
    }
}

From source file:com.amalto.core.metadata.ClassRepository.java

private static boolean isClassMethod(Class clazz, Method declaredMethod) {
    Class superClass = clazz.getSuperclass();
    if (!Object.class.equals(superClass)) {
        try {/*from www  . jav a  2  s.c om*/
            return superClass.getMethod(declaredMethod.getName(), declaredMethod.getParameterTypes()) != null;
        } catch (NoSuchMethodException e) {
            return true;
        }
    }
    return true;
}

From source file:com.springframework.beans.BeanUtils.java

/**
 * Find a method with the given method name and the given parameter types,
 * declared on the given class or one of its superclasses. Prefers public methods,
 * but will return a protected, package access, or private method too.
 * <p>Checks {@code Class.getMethod} first, falling back to
 * {@code findDeclaredMethod}. This allows to find public methods
 * without issues even in environments with restricted Java security settings.
 * @param clazz the class to check//from  www .j a v a2  s  . com
 * @param methodName the name of the method to find
 * @param paramTypes the parameter types of the method to find
 * @return the Method object, or {@code null} if not found
 * @see Class#getMethod
 * @see #findDeclaredMethod
 */
public static Method findMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    try {
        return clazz.getMethod(methodName, paramTypes);
    } catch (NoSuchMethodException ex) {
        return findDeclaredMethod(clazz, methodName, paramTypes);
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.xmi.importer.XmiHelper.java

/**
 * Returns the WriteMethod for the given EStructuralFeature
 * /* w w  w .  j  av a 2 s.c o  m*/
 * @param esf the given EStructuralFeature
 * @param entityClass the entity class to get the method from
 * @return the corresponding WriteMethod
 */
public static Method getWriteMethod(EStructuralFeature esf, Class<? extends IdEntity> entityClass) {
    try {
        String methodName = "set" + StringUtils.capitalize(esf.getName());
        Class<?> firstMethodParameterType = getReadMethod(esf, entityClass).getReturnType();

        return entityClass.getMethod(methodName, firstMethodParameterType);
    } catch (NoSuchMethodException e) {
        LOGGER.error(e);
    } catch (SecurityException e) {
        LOGGER.error(e);
    }

    LOGGER.error("No setMethod for:" + esf.getName());

    return null;
}

From source file:com.prowidesoftware.swift.model.SwiftMessageUtils.java

public static SwiftTagListBlock createSequenceSingle(final Class<? extends AbstractMT> mt,
        final String sequenceName, final Tag... tags) {
    final String cn = mt.getName() + "$Sequence" + sequenceName;
    try {//from   w ww.j a v  a  2 s .  co  m
        final Class<?> subSequenceClass = Class.forName(cn);
        final Method method = subSequenceClass.getMethod("newInstance", Tag[].class);
        return (SwiftTagListBlock) method.invoke(null, new Object[] { tags });
    } catch (Exception e) {
        log.log(Level.WARNING, "Reflection error: mt=" + mt.getName() + ", sequenceName=" + sequenceName
                + ", tags=" + tags + " - " + e, e);
        throw new WifeException("Reflection error: mt=" + mt.getName() + ", sequenceName=" + sequenceName
                + ", tags=" + tags + " - " + e);
    }
}