Java Reflection Method Getter Invoke invokeGetter(Object object, String field)

Here you can find the source of invokeGetter(Object object, String field)

Description

invoke Getter

License

Apache License

Declaration

public static Object invokeGetter(Object object, String field)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException 

Method Source Code


//package com.java2s;
/*//ww w.j a va2 s . c  o m
 * Copyright 2007-2013 Ben Galbraith.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static Object invokeGetter(Object object, String field)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Method method = getGetterMethod(object.getClass(), field);
        return method.invoke(object);
    }

    public static Method getGetterMethod(Class type, String property) throws NoSuchMethodException {
        String getName = getEtterMethodName(property, "get");
        try {
            return type.getMethod(getName);
        } catch (NoSuchMethodException e) {
            try {
                getName = getEtterMethodName(property, "is");
                return type.getMethod(getName);
            } catch (Exception e1) {
                throw new NoSuchMethodException(
                        "No getter found for property '" + property + "' using 'is', 'has', and 'get' prefixes");
            }
        }
    }

    public static String getEtterMethodName(String property, String type) {
        return type + property.substring(0, 1).toUpperCase() + property.substring(1);
    }
}

Related

  1. invokeGetter(Object entity, String propertyName)
  2. invokeGetter(Object getterOwner, Method method)
  3. invokeGetter(Object o, String name, boolean forceAccess)
  4. invokeGetter(Object obj, String methodName)
  5. invokeGetter(Object obj, String methodName, int defaultValue)
  6. invokeGetter(Object target, Method getter)
  7. invokeGetterMethod(final Method method, final Object object)
  8. invokeGetterSafe(Object o, String name, boolean forceAccess)
  9. invokeSetter(Object target, Class clazz, String methodName, String getterMethod, Object param)