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.softmotions.commons.bean.BeanUtils.java

/**
 * Sets a property at the given bean.//  w ww.  j a v a2  s  .  c o m
 *
 * @param bean         The bean to set a property at.
 * @param propertyName The name of the property to set.
 * @param value        The value to set for the property.
 * @throws BeanException In case the bean access failed.
 */
public static void setProperty(Object bean, String propertyName, Object value) throws BeanException {
    Class valueClass = null;
    try {
        // getting property object from bean using "setNnnn", where nnnn is parameter name
        Method setterMethod = null;
        // first trying form getPropertyNaae for regular value
        String setterName = "set" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
        Class paramClass = bean.getClass();
        if (value != null) {
            valueClass = value.getClass();
            Class[] setterArgTypes = new Class[] { valueClass };
            setterMethod = paramClass.getMethod(setterName, setterArgTypes);
        } else {
            Method[] methods = paramClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method m = methods[i];
                if (m.getName().equals(setterName) && (m.getParameterTypes().length == 1)) {
                    setterMethod = m;
                    break;
                }
            }
        }
        if (setterMethod == null) {
            throw new NoSuchMethodException(setterName);
        }
        Object[] setterArgs = new Object[] { value };
        setterMethod.invoke(bean, setterArgs);
    } catch (NoSuchMethodError | NoSuchMethodException ex) {
        throw new BeanException("No setter method found for property '" + propertyName + "' and type "
                + valueClass + " at given bean from class " + bean.getClass().getName() + ".", ex);
    } catch (InvocationTargetException ex) {
        throw new BeanException("Property '" + propertyName + "' could not be set for given bean from class "
                + bean.getClass().getName() + ".", ex);
    } catch (IllegalAccessException ex) {
        throw new BeanException("Property '" + propertyName
                + "' could not be accessed for given bean from class " + bean.getClass().getName() + ".", ex);
    }
}

From source file:Main.java

/**
 * invoke the leftParameter and get the name property.
 * it will try the Array.length() and Map.get(),
 * then it will try get'Name' and is'Name',
 * last, it will to find the name by invoke field.
 *///from  w  w w  .ja v a2s  .c om
public static Object searchProperty(Object leftParameter, String name) throws Exception {
    Class<?> leftClass = leftParameter.getClass();
    Object result;
    if (leftParameter.getClass().isArray() && "length".equals(name)) {
        result = Array.getLength(leftParameter);
    } else if (leftParameter instanceof Map) {
        result = ((Map<Object, Object>) leftParameter).get(name);
    } else {
        try {
            String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = leftClass.getMethod(getter, new Class<?>[0]);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            result = method.invoke(leftParameter, new Object[0]);
        } catch (NoSuchMethodException e2) {
            try {
                String getter = "is" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = leftClass.getMethod(getter, new Class<?>[0]);
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                result = method.invoke(leftParameter, new Object[0]);
            } catch (NoSuchMethodException e3) {
                Field field = leftClass.getField(name);
                result = field.get(leftParameter);
            }
        }
    }
    return result;
}

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

public static Object invoke(Object target, Object[] methodName, Object param) throws Throwable {
    List results = new ArrayList();
    try {//from  w  w  w  .  j av  a  2s  . c  om
        Class cls = target.getClass();
        Class[] paramTypes = new Class[] { Object.class };
        for (int i = 0; i < methodName.length; i++) {
            Method method = cls.getMethod((String) methodName[i], paramTypes);
            Object obj = method.invoke(target, param);
            if (obj != null) {
                results.add(obj);
            }
        }
    } catch (Throwable e) {
        if (e.getCause() instanceof AWException) {
            e.getCause().printStackTrace();
            throw (AWException) e.getCause();
        }
        e.printStackTrace();
        throw e;
    }
    return results;
}

From source file:Main.java

private static <T> String toXml(T t, String head) {
    if (null == t) {
        return "";
    }//from  w w  w.jav a 2  s  .c om
    StringBuilder sb = new StringBuilder();
    sb.append(String.format("<%s>", head)).append("\n");
    if (t instanceof Collection<?>) {
        Collection<?> collection = (Collection<?>) t;
        for (Object object : collection) {
            sb.append(toXml(object, "item"));
        }
    } else {
        Class<?> clazz = t.getClass();
        Method[] methods = clazz.getMethods();
        try {
            for (Method method : methods) {
                String methodName = method.getName();
                if (methodName.startsWith("get")) {
                    String key = methodName.substring(3);
                    Method setMethod = null;
                    try {
                        setMethod = clazz.getMethod("set" + key, method.getReturnType());
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    if (null != setMethod) {
                        Object value = method.invoke(t);
                        if (method.getReturnType() == String.class) {
                            try {
                                String stringValue = (String) method.invoke(t);
                                if (null != stringValue) {
                                    try {
                                        Integer.parseInt(stringValue);
                                        sb.append(String.format("<%s>%s</%s>\n", key, stringValue, key));
                                    } catch (Exception e) {
                                        sb.append(String.format("<%s><![CDATA[%s]]></%s>\n", key, stringValue,
                                                key));

                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            sb.append(toXml(value, key));
                        }
                    }
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    sb.append(String.format("</%s>\n", head));
    return sb.toString();
}

From source file:ch.aonyx.broker.ib.api.util.AnnotationUtils.java

private static <A extends Annotation> A searchOnInterfaces(final Method method, final Class<A> annotationType,
        final Class<?>[] ifcs) {
    A annotation = null;//w ww .  j ava 2 s. co  m
    for (final Class<?> iface : ifcs) {
        if (isInterfaceWithAnnotatedMethods(iface)) {
            try {
                final Method equivalentMethod = iface.getMethod(method.getName(), method.getParameterTypes());
                annotation = getAnnotation(equivalentMethod, annotationType);
            } catch (final NoSuchMethodException ex) {
                // Skip this interface - it doesn't have the method...
            }
            if (annotation != null) {
                break;
            }
        }
    }
    return annotation;
}

From source file:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Try to clone the given object./*from  w  ww. j  av  a  2  s.  c o  m*/
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectUtils.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        Class<?> clazz = object.getClass();
        Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionUtils.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static Object searchProperty(Object leftParameter, String name) throws Exception {
    Class<?> leftClass = leftParameter.getClass();
    Object result;//from w  w  w  . j a va  2s  .  c o m
    if (leftParameter.getClass().isArray() && "length".equals(name)) {
        result = Array.getLength(leftParameter);
    } else if (leftParameter instanceof Map) {
        result = ((Map<Object, Object>) leftParameter).get(name);
    } else {
        try {
            String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = leftClass.getMethod(getter, new Class<?>[0]);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            result = method.invoke(leftParameter, new Object[0]);
        } catch (NoSuchMethodException e2) {
            try {
                String getter = "is" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = leftClass.getMethod(getter, new Class<?>[0]);
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                result = method.invoke(leftParameter, new Object[0]);
            } catch (NoSuchMethodException e3) {
                Field field = leftClass.getField(name);
                result = field.get(leftParameter);
            }
        }
    }
    return result;
}

From source file:ReflectUtil.java

/**
 * <p>Attempts to find an accessible version of the method passed in, where accessible
 * is defined as the method itself being public and the declaring class being public.
 * Mostly useful as a workaround to the situation when
 * {@link PropertyDescriptor#getReadMethod()} and/or
 * {@link java.beans.PropertyDescriptor#getWriteMethod()} returns methods that are not
 * accessible (usually due to public implementations of interface methods in private
 * classes).</p>/*from w  ww.  ja  v  a 2 s  . co m*/
 *
 * <p>Checks the method passed in and if it already meets these criteria it is returned
 * immediately. In general this leads to very little performance overhead</p>
 *
 * <p>If the method does not meet the criteria then the class' interfaces are scanned
 * for a matching method. If one is not found, then the class' superclass hierarchy
 * is searched. Finally, if no matching method can be found the original method is
 * returned.</p>
 *
 * @param m a method that may or may not be accessible
 * @return either an accessible version of the same method, or the method passed in if
 *         an accessible version cannot be found
 */
public static Method findAccessibleMethod(final Method m) {
    // If the passed in method is accessible, then just give it back.
    if (isPublic(m.getModifiers()) && isPublic(m.getDeclaringClass().getModifiers()))
        return m;
    if (m.isAccessible())
        return m;

    final Class<?> clazz = m.getDeclaringClass();
    final String name = m.getName();
    final Class<?>[] ptypes = m.getParameterTypes();

    // Else, loop through the interfaces for the declaring class, looking for a
    // public version of the method that we can call
    for (Class<?> iface : clazz.getInterfaces()) {
        try {
            Method m2 = iface.getMethod(name, ptypes);
            if (m2.isAccessible())
                return m2;
            if (isPublic(iface.getModifiers()) && isPublic(m2.getModifiers()))
                return m2;
        } catch (NoSuchMethodException nsme) {
            /* Not Unexpected. */ }
    }

    // Else loop through the superclasses looking for a public method
    Class<?> c = clazz.getSuperclass();
    while (c != null) {
        try {
            Method m2 = c.getMethod(name, ptypes);
            if (m2.isAccessible())
                return m2;
            if (isPublic(c.getModifiers()) && isPublic(m2.getModifiers()))
                return m2;
        } catch (NoSuchMethodException nsme) {
            /* Not Unexpected. */ }

        c = c.getSuperclass();
    }

    // If we haven't found anything at this point, just give up!
    return m;
}

From source file:edu.cornell.mannlib.vedit.util.FormUtils.java

private static Method getSetterMethod(Class beanClass, String fieldName, List<Class> supportedTypes) {
    for (Class clazz : supportedTypes) {
        try {//  w  ww.j a va  2s  .  co m
            Class[] argList = new Class[1];
            argList[0] = clazz;
            return beanClass.getMethod("set" + fieldName, argList);
        } catch (NoSuchMethodException nsme) {
            // just try the next type
        }
    }
    return null;
}

From source file:com.acrutiapps.browser.ui.components.CustomWebView.java

private static void loadMethods() {
    try {/*from   w w w  . ja  v a 2s . co  m*/

        // 15 is ICS 2nd release.
        if (android.os.Build.VERSION.SDK_INT > 15) {
            // WebSettings became abstract in JB, and "setProperty" moved to the concrete class, WebSettingsClassic,
            // not present in the SDK. So we must look for the class first, then for the methods.
            ClassLoader classLoader = CustomWebView.class.getClassLoader();
            Class<?> webSettingsClassicClass = classLoader.loadClass("android.webkit.WebSettingsClassic");
            sWebSettingsSetProperty = webSettingsClassicClass.getMethod("setProperty",
                    new Class[] { String.class, String.class });
        } else {
            sWebSettingsSetProperty = WebSettings.class.getMethod("setProperty",
                    new Class[] { String.class, String.class });
        }

    } catch (NoSuchMethodException e) {
        Log.e("CustomWebView", "loadMethods(): " + e.getMessage());
        sWebSettingsSetProperty = null;
    } catch (ClassNotFoundException e) {
        Log.e("CustomWebView", "loadMethods(): " + e.getMessage());
        sWebSettingsSetProperty = null;
    }

    sMethodsLoaded = true;
}