Example usage for java.lang.reflect Method getName

List of usage examples for java.lang.reflect Method getName

Introduction

In this page you can find the example usage for java.lang.reflect Method getName.

Prototype

@Override
public String getName() 

Source Link

Document

Returns the name of the method represented by this Method object, as a String .

Usage

From source file:com.softmotions.commons.bean.BeanUtils.java

/**
 * Sets a property at the given bean./*from  w  ww. j a  va2  s  .c  om*/
 *
 * @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:net.servicefixture.util.ReflectionUtils.java

private static void setProperty(Object parent, String attributeName, Object source) throws Exception {
    Method[] methods = parent.getClass().getMethods();
    for (Method method : methods) {
        if (method.getName().startsWith("set") && method.getName().length() > 3
                && StringUtils.uncapitalize(method.getName().substring(3)).equals(attributeName)
                && method.getParameterTypes().length == 1
                && (source == null || method.getParameterTypes()[0].isAssignableFrom(source.getClass()))) {
            method.invoke(parent, source);
            return;
        }// ww  w . jav  a 2 s  . com
    }
    BeanUtils.setProperty(parent, attributeName, source);
}

From source file:com.qrmedia.commons.persistence.hibernate.clone.HibernateEntityBeanCloner.java

private static Collection<String> getPropertyNames(Collection<Method> methods) {
    Collection<String> methodNames = new ArrayList<String>();

    /*//from   w w w .ja  va  2 s. c  o  m
     * If a method is an instance method, does not return void, takes no parameters 
     * and is named "get..." (it's assumed to be public), add the corresponding field name.
     */
    for (Method method : methods) {
        assert Modifier.isPublic(method.getModifiers()) : method;
        String methodName = method.getName();
        Matcher getterNameMatcher = GETTER_PREFIX.matcher(methodName);

        if (!Modifier.isStatic(method.getModifiers()) && (method.getReturnType() != Void.class)
                && (method.getParameterTypes().length == 0) && getterNameMatcher.matches()) {

            // the first group is the (uppercase) first letter of the field name
            methodNames.add(getterNameMatcher.replaceFirst(getterNameMatcher.group(1).toLowerCase() + "$2"));
        }

    }

    return methodNames;
}

From source file:Main.java

/**
 * find the setter method and set the value.
 *//*from  w  w  w  . j a  va 2s.c  o  m*/
public static void setProperties(Object bean, Map<String, Object> properties) {
    for (Method method : bean.getClass().getMethods()) {
        String name = method.getName();
        if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(method.getModifiers())
                && method.getParameterTypes().length == 1 && method.getDeclaringClass() != Object.class) {
            String key = name.substring(3, 4).toLowerCase() + name.substring(4);
            try {
                Object value = properties.get(key);
                if (value != null) {
                    method.invoke(bean,
                            new Object[] { convertCompatibleType(value, method.getParameterTypes()[0]) });
                }
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.ms.commons.test.common.ReflectUtil.java

public static Method getDeclaredMethod(Class<?> clazz, String methodName) {
    try {/* w  w w  .j  a  v  a 2  s .  c  om*/
        Method foundMethod = null;
        Method[] methods = clazz.getDeclaredMethods();
        for (Method m : methods) {
            if (methodName.equals(m.getName())) {
                if (foundMethod != null) {
                    throw new RuntimeException("Found two method named: " + methodName + " in class: " + clazz);
                }
                foundMethod = m;
            }
        }
        if (foundMethod == null) {
            throw new NoSuchMethodException("Cannot find method named: " + methodName + " in class: " + clazz);
        }
        return foundMethod;
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        if (clazz == Object.class) {
            return null;
        } else {
            return getDeclaredMethod(clazz.getSuperclass(), methodName);
        }
    }
}

From source file:edu.mayo.cts2.framework.model.util.ModelUtils.java

/**
 * Sets the entity./*from   w ww .  j a  v  a 2 s . c  o m*/
 *
 * @param wrapper the wrapper
 * @param entityDescription the entity description
 */
public static void setEntity(EntityDescription wrapper, EntityDescriptionBase entityDescription) {
    try {
        for (Method method : EntityDescription.class.getDeclaredMethods()) {
            if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0].equals(entityDescription.getClass())) {
                method.invoke(wrapper, entityDescription);
            }
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.starlink.rest.util.Reflections.java

/**
 * ?, ?DeclaredMethod,?./*  w  ww. j  a v a 2s  .  c  om*/
 * ?Object?, null.
 * ????
 *
 * ?. ?Method,?Method.invoke(Object obj, Object... args)
 */
public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
    Validate.notNull(obj, "object can't be null");
    Validate.notBlank(methodName, "methodName can't be blank");
    Assert.assertNotNull("object can't be null", obj);
    for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType
            .getSuperclass()) {
        Method[] methods = searchType.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                makeAccessible(method);
                return method;
            }
        }
    }
    return null;
}

From source file:com.yimidida.shards.utils.ParameterUtil.java

/**
 * ??//from   www  .ja  v  a  2  s  . co m
 * 
 * @param obj
 * @param shardId
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object resolve(final Object obj, final ShardId shardId) {
    try {
        // 
        if (obj instanceof String || obj instanceof Number || obj instanceof Boolean
                || obj instanceof Character) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(HashMap.class);
            enhancer.setCallback(new MethodInterceptor() {

                private final String prefix = shardId.getPrefix();
                private final String suffix = shardId.getSuffix();
                private final Object parameter = obj;

                @Override
                public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy)
                        throws Throwable {

                    if ("containsKey".equals(method.getName())) {
                        //MapcontainsKey?TRUE
                        return true;
                    }

                    if (args.length > 0 && "get".equals(method.getName())) {
                        if ("prefix".equals(args[0])) {
                            return prefix;
                        } else if ("suffix".equals(args[0])) {
                            return suffix;
                        } else {
                            return parameter;
                        }
                    }

                    return proxy.invokeSuper(object, args);
                }
            });

            return (HashMap) enhancer.create();
        } else if (obj instanceof Map) {
            Map parameter = (Map) obj;
            parameter.put("prefix", shardId.getPrefix());
            parameter.put("suffix", shardId.getSuffix());

            return parameter;
        } else if (obj instanceof List) {
            Map<String, Object> parameter = Maps.newHashMap();
            parameter.put("list", obj);
            parameter.put("prefix", shardId.getPrefix());
            parameter.put("suffix", shardId.getSuffix());

            return parameter;
        } else if (obj != null && obj.getClass().isArray()) {
            Map<String, Object> parameter = Maps.newHashMap();
            parameter.put("array", obj);
            parameter.put("prefix", shardId.getPrefix());
            parameter.put("suffix", shardId.getSuffix());

            return parameter;
        } else if (obj instanceof Object) {
            Map<String, Object> parameter = PropertyUtils.describe(obj);
            parameter.put("prefix", shardId.getPrefix());
            parameter.put("suffix", shardId.getSuffix());

            return parameter;
        } else if (obj != null) {
            throw new UnsupportedOperationException(
                    String.format("The parameter of type {%s} is not supported.", obj.getClass()));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return null;
}

From source file:org.dimitrovchi.conf.service.ServiceParameterUtils.java

public static String reflectToString(String name, Object proxy) {
    final Map<String, Object> map = new LinkedHashMap<>();
    for (final Method method : proxy.getClass().getMethods()) {
        if (method.getDeclaringClass() == Object.class || method.getDeclaringClass() == Proxy.class) {
            continue;
        }// w  w w .j a va2  s .  co m
        switch (method.getName()) {
        case "toString":
        case "hashCode":
        case "annotationType":
            continue;
        }
        if (method.getParameterCount() == 0) {
            try {
                map.put(method.getName(), method.invoke(proxy));
            } catch (ReflectiveOperationException x) {
                throw new IllegalStateException(x);
            }
        }
    }
    return name + map;
}

From source file:com.espertech.esper.event.vaevent.PropertyUtility.java

private static PropertyAccessException getAccessExceptionMethod(Method method, Exception e) {
    Class declaring = method.getDeclaringClass();
    String message = "Failed to invoke method " + method.getName() + " on class "
            + JavaClassHelper.getClassNameFullyQualPretty(declaring) + ": " + e.getMessage();
    throw new PropertyAccessException(message, e);
}