Return the accessor method for attribute with specified name. - Java Reflection

Java examples for Reflection:Method Name

Description

Return the accessor method for attribute with specified name.

Demo Code


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

import javax.management.openmbean.OpenDataException;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class type = String.class;
        String name = "java2s.com";
        System.out.println(getAccessor(type, name));
    }/*  w w  w .ja  va  2 s  . c o  m*/

    /** Prefix for all isser accessor methods. */
    private static final String IS_ACCESSOR_PREFIX = "is";
    /** Prefix for all getter accessor methods. */
    private static final String GET_ACCESSOR_PREFIX = "get";

    /**
     * Return the accessor method for attribute with specified name.
     *
     * @param type the type to retrieve method from.
     * @param name the name of the attribute.
     * @return the accessor method if any.
     * @throws OpenDataException if unable to find accessor method.
     */
    public static Method getAccessor(final Class type, final String name)
            throws OpenDataException {
        final String baseName = Character.toUpperCase(name.charAt(0))
                + name.substring(1);
        try {
            final String accessorName = GET_ACCESSOR_PREFIX + baseName;
            return type.getMethod(accessorName, new Class[0]);
        } catch (final NoSuchMethodException nsme) {
            //try for "isX()" style getter
            try {
                final String accessorName = IS_ACCESSOR_PREFIX + name;
                final Method accessor = type.getMethod(accessorName,
                        new Class[0]);
                final Class returnType = accessor.getReturnType();
                if (Boolean.TYPE != returnType) {
                    final String message = "Accessor named " + accessorName
                            + " should return a boolean value.";
                    throw new OpenDataException(message);
                }
                return accessor;
            } catch (final NoSuchMethodException nsme2) {
                final String message = "Missing accessor for field " + name;
                throw new OpenDataException(message);
            }
        }
    }
}

Related Tutorials