Java Reflection Method Getter Get getGetterFor(Object obj, Field field, Class objClass)

Here you can find the source of getGetterFor(Object obj, Field field, Class objClass)

Description

get Getter For

License

Open Source License

Declaration

private static Method getGetterFor(Object obj, Field field, Class objClass) 

Method Source Code


//package com.java2s;
/*//from  w ww .j  a v a2s  .  c o  m
 * #%L
 * Katsu Commons
 * %%
 * Copyright (C) 2013 Katsu
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {
    private static Method getGetterFor(Object obj, Field field, Class objClass) {
        for (Method m : objClass.getDeclaredMethods()) {
            if (m.getName().equals(getGetterMethodName(field.getName(), false))
                    || m.getName().equals(getGetterMethodName(field.getName(), true))) {
                if (m.getGenericParameterTypes().length == 0) {
                    return m;
                }
            }
        }
        //Su super class
        Class c = objClass.getSuperclass();
        if (c != null) {
            return getGetterFor(obj, field, c);
        }
        return null;
    }

    private static String getGetterMethodName(String fieldName, boolean is) {
        if (is) {
            if (fieldName.startsWith("is"))
                fieldName = fieldName.substring(2, fieldName.length());
            return "is" + firstCharUpper(fieldName);

        } else {
            return "get" + firstCharUpper(fieldName);

        }
    }

    private static String firstCharUpper(String cad) {
        String first = cad.substring(0, 1).toUpperCase();
        String aux = cad.substring(1);
        return first + aux;
    }
}

Related

  1. getGetter(String propertyName, Class clazz)
  2. getGetterAttributeType(Method m)
  3. getGetterFieldName(Method method)
  4. getGetterFields(final Class clazz)
  5. getGetterFor(Field field)
  6. getGetterFromCache(Class clazz)
  7. getGetterFromProperty(Class clazz, String property)
  8. getGetterMethod(Class containingClass, String propertyName)
  9. getGetterMethod(Class type, String property)