集册 Java实例教程 从方法名称获取Java Bean属性名称

从方法名称获取Java Bean属性名称

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

547
从方法名称获取Java Bean属性名称
/*n o w j a v a . c o m - 时  代  Java*/

/**

 * JLibs: Common Utilities for Java

 * Copyright (C) 2009  Santhosh Kumar T <santhosh.tekuri@gmail.com>

 *

 * This library is free software; you can redistribute it and/or

 * modify it under the terms of the GNU Lesser General Public

 * License as published by the Free Software Foundation; either

 * version 2.1 of the License, or (at your option) any later version.

 *

 * This library is distributed in the hope that it will be useful,

 * but WITHOUT ANY WARRANTY; without even the implied warranty of

 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU

 * Lesser General Public License for more details.

 */

//package com.nowjava;


import java.util.Locale;


public class Main {

    public static void main(String[] argv) throws Exception {

        String methodName = "nowjava.com";

        System.out.println(getPropertyName(methodName));

    }


    /** prefix used by non-boolean getter methods */

    public static final String GET = "get";

    /** prefix used by boolean getter methods */

    public static final String IS = "is";

    /** prefix used by setter methods */

    public static final String SET = "set";


    @SuppressWarnings({ "ConstantConditions" })
    /*
    时 代 J a v a 公 众 号 - nowjava.com
    */

    public static String getPropertyName(String methodName) {

        String suffix;

        if (methodName.startsWith(GET) || methodName.startsWith(SET))

            suffix = methodName.substring(3);

        else if (methodName.startsWith(IS))

            suffix = methodName.substring(2);

        else

            throw new IllegalArgumentException("invalid method name: "

                    + methodName);


        switch (suffix.length()) {

        case 0:

            throw new IllegalArgumentException("invalid method name: "

                    + methodName);

        case 1:

            return suffix.toLowerCase(Locale.ENGLISH);

        default:

            char char0 = suffix.charAt(0);

            boolean upper0 = Character.isUpperCase(char0);

            char char1 = suffix.charAt(1);

            boolean upper1 = Character.isUpperCase(char1);

            if (upper0 && upper1) // getXCordinate() ==> XCoordinate

                return su
展开阅读全文