集册 Java实例教程 返回具有指定名称的属性的访问器方法。

返回具有指定名称的属性的访问器方法。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

473
返回具有指定名称的属性的访问器方法。


//package com.nowjava;
/*来自 
 时代Java公众号 - N o w J a  v a . c o m*/

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 = "nowjava.com";

        System.out.println(getAccessor(type, name));

    }

    /*
     from NowJava.com 
    */

    /** 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.";

                    
展开阅读全文