Return true if method matches naming convention for accessor. - Java Reflection

Java examples for Reflection:Method Return

Description

Return true if method matches naming convention for accessor.

Demo Code


//package com.java2s;
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 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";

    /**//from  w  w w.j  a va  2  s  . c o  m
     * Return true if method matches naming convention for accessor.
     *
     * @param method the method.
     * @return true if method matches naming convention for accessor.
     */
    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;
        }
    }
}

Related Tutorials