Java Reflection Method Setter Get getSetter(final Object o, final String fieldName)

Here you can find the source of getSetter(final Object o, final String fieldName)

Description

Returns the method of a given object which is the setter-method of a given field whose name is expected to be like setFieldname.

License

Open Source License

Parameter

Parameter Description
o The object containing the setter-method.
fieldName The field whose setter-method is desired

Return

the reflected method. Is null if method was not found in the given object

Declaration

public static Method getSetter(final Object o, final String fieldName) 

Method Source Code

//package com.java2s;
/**/* w  w w  .  j a  v a 2s. c o m*/
 * Made by Kay Lerch (https://twitter.com/KayLerch)
 *
 * Attached license applies.
 * This library is licensed under GNU GENERAL PUBLIC LICENSE Version 3 as of 29 June 2007
 */

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;

public class Main {
    /**
     * Returns the method of a given object which is the setter-method of a given field
     * whose name is expected to be like setFieldname. Returns null if method not found.
     * @param o The object containing the setter-method.
     * @param fieldName The field whose setter-method is desired
     * @return the reflected method. Is null if method was not found in the given object
     */
    public static Method getSetter(final Object o, final String fieldName) {
        return getMethodWithPrefix(o, fieldName, "set").orElse(null);
    }

    /**
     * Returns any method whose name starts with given prefix and ends with given fieldname where
     * first letter of the fieldname will be uppercased.
     * @param o The object containing the desired method.
     * @param fieldName The fieldname contained in the name of the desired method.
     * @param prefix A prefix string of the method-name
     * @return The reflected method. Is empty if method was not found.
     */
    private static Optional<Method> getMethodWithPrefix(final Object o, final String fieldName,
            final String prefix) {
        final String methodName = prefix + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
        return Arrays.stream(o.getClass().getMethods()).filter(method -> method.getName().equals(methodName))
                .findFirst();
    }
}

Related

  1. getSetter(Class clazz, String property, Class type)
  2. getSetter(Class cls, final String fieldName)
  3. getSetter(final Class targetClass, final String propertyName)
  4. getSetter(final Class clazz, final String fieldName, final Class... fieldClass)
  5. getSetter(final Class clz, final String propertyName, final Class propertyClass)
  6. getSetter(Method m)
  7. getSetter(Object instance, String methodName)
  8. getSetter(Object object, String name, Class type)
  9. getSetter(Object target, String property, Class parameterType)