Invoke the getter Method for the given source object. - Java Reflection

Java examples for Reflection:Getter

Description

Invoke the getter Method for the given source object.

Demo Code


//package com.java2s;
import java.lang.reflect.Method;

public class Main {
    /**/* www. j a  va  2 s .c om*/
     * Invoke the getterMethod for the given source object.
     *
     * @param getterMethod the getter method to invoke
     * @param source the source object to invoke the getter method on
     * @param property the getter method property name (used for logging)
     * @param path the full expression path (used for logging)
     * @return the getter result
     */
    public final static Object invokeGetter(Method getterMethod,
            Object source, String property, String path) {

        try {
            // Retrieve target object from getter
            return getterMethod.invoke(source, new Object[0]);

        } catch (Exception e) {
            // Log detailed error message of why getter failed
            StringBuilder buffer = new StringBuilder();
            buffer.append("Result: error occurred while trying to get");
            buffer.append(" instance of '");
            buffer.append(getterMethod.getReturnType().getName());
            buffer.append("' using method: '");
            buffer.append(getterMethod.getName()).append("()' of class '");
            buffer.append(source.getClass().getName()).append("'.");
            throw new RuntimeException(buffer.toString(), e);
        }
    }
}

Related Tutorials