Returns a Method object corresponding to a getter that retrieves an instance of componentClass from target. - Java Reflection

Java examples for Reflection:Getter

Description

Returns a Method object corresponding to a getter that retrieves an instance of componentClass from target.

Demo Code


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

public class Main {


    /**//  ww w . j av a 2 s  .  c o  m
     * Returns a Method object corresponding to a getter that retrieves an instance of componentClass from target.
     *
     * @param target         class that the getter should exist on
     * @param componentClass component to get
     * @return Method object, or null of one does not exist
     */
    public static Method getterMethod(Class<?> target,
            Class<?> componentClass) {
        try {
            return target.getMethod(getterName(componentClass));
        } catch (NoSuchMethodException e) {
            //if (log.isTraceEnabled()) log.trace("Unable to find method " + getterName(componentClass) + " in class " + target);
            return null;
        } catch (NullPointerException e) {
            return null;
        }
    }

    /**
     * Returns a getter for a given class
     *
     * @param componentClass class to find getter for
     * @return name of getter method
     */
    public static String getterName(Class<?> componentClass) {
        if (componentClass == null)
            return null;
        StringBuilder sb = new StringBuilder("get");
        sb.append(componentClass.getSimpleName());
        return sb.toString();
    }
}

Related Tutorials