集册 Java实例教程 如果method是访问器或更改器,则返回true。

如果method是访问器或更改器,则返回true。

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

494
如果method是访问器或更改器,则返回true。

/*
 from 时代Java - N o w  J a v a . c o m 
*/

//package com.nowjava;

import java.lang.reflect.Method;

import java.lang.reflect.Type;


public class Main {

    /** getClass() method name. */

    private static final String GET_CLASS_METHOD_NAME = "getClass";

    /** Prefix for all mutator methods. */

    private static final String MUTATOR_PREFIX = "set";

    /** 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 true if method is either an accessor or a mutator.

     *

     * @param method the method.

     * @return true if method is either an accessor or a mutator.

     */

    public static boolean isAttributeMethod(final Method method) {

        return isAccessor(method) || isMutator(method);

    }


    /**

     * Return true if method matches naming convention for accessor.

     *

     * @param method the method.

     * @return true if method matches naming convention for accessor.

     */
     /*
     n  o  w  j  a  v  a . c o m
     */

    public static boolean isAccessor(final Method method) {

        final Type type = method.getGenericReturnType();

        if (Void.TYPE == type || method.getParameterTypes().length != 0) {

            return false;

        }

        final String name = method.getName();

        if (name.startsWith(GET_ACCESSOR_PREFIX) && name.length() > 3

                && !GET_CLASS_METHOD_NAME.equals(name)) {

            return true;

        } else {

            return name.startsWith(IS_ACCESSOR_PREFIX) && name.length() > 2

                    && Boolean.TYPE == type;

        }

    }


    
展开阅读全文