集册 Java实例教程 返回方法的属性名称。

返回方法的属性名称。

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

425
返回方法的属性名称。
/*
 from N  o w  J a v a . c o m 
*/

/*

 * Copyright 2002-2006,2009 The Apache Software Foundation.

 * 

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 * 

 *      http://www.apache.org/licenses/LICENSE-2.0

 * 

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

//package com.nowjava;


import java.lang.reflect.Method;


import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class Main {

    private static final Pattern SETTER_PATTERN = Pattern

            .compile("set([A-Z][A-Za-z0-9]*)$");

    private static final Pattern GETTER_PATTERN = Pattern

            .compile("(get|is|has)([A-Z][A-Za-z0-9]*)$");


    /**

     * Returns the property name for a method.

     * This method is independant from property fields.

     *

     * @param method The method to get the property name for.

     * @return the property name for given method; null if non could be resolved.

     */

    public static String resolvePropertyName(Method method) {
// from n  o  w  j  a  v  a . c o m

        Matcher matcher = SETTER_PATTERN.matcher(method.getName());

        if (matcher.matches() && method.getParameterTypes().length == 1) {

            String raw = matcher.group(1);

            return raw.substring(0, 1).toLowerCase() + raw.substrin
展开阅读全文