find Setter from a class by name using reflection - Java Reflection

Java examples for Reflection:Java Bean

Description

find Setter from a class by name using reflection

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        String fieldName = "java2s.com";
        System.out.println(findSetter(clazz, fieldName));
    }/*from   w  w  w .  ja  v a2 s  .c om*/

    public static Method findSetter(Class<?> clazz, String fieldName) {
        List<Method> methods = findMethod(clazz, calcSetterName(fieldName));
        methods.addAll(findMethod(clazz, fieldName));

        for (Method method : methods) {
            if (method != null && method.getParameterTypes().length == 1)
                return method;
        }

        return null;
    }

    public static List<Method> findMethod(Class<?> clazz, String name) {
        List<Method> ret = new ArrayList<Method>();
        for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
            Method[] methods = (c.isInterface() ? c.getMethods() : c
                    .getDeclaredMethods());
            for (Method method : methods) {
                if (name.equals(method.getName()))
                    ret.add(method);
            }
        }
        return ret;
    }

    public static String calcSetterName(String fieldName) {
        return "set" + ucfirst(fieldName);
    }

    public static String ucfirst(String str) {
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }
}

Related Tutorials