深刻了解JavaBean規範中的屬性名和setter/getter方法

JavaBean規範文檔:http://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/java

關於屬性名的部分:api

Utility method to take a string and convert it to normal Java variable name capitalization. This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone. Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".oracle

工具翻譯+我的修改:工具

工具方法把一個字符串並將其轉換爲正常的Java變量名的大寫。這一般意味着將第一個字符從大寫轉換爲小寫, 但在(特殊)的特殊狀況下,當前兩個字符或多個字符是大寫時,咱們不處理他(直接返回)。測試

所以,「Foobah」變成了「foobah」和「X」變成了「x」,但「URL」仍然是「URL」。翻譯

以上的內容其實是java.bean.Introspector#decapitalize這個方法的javadoc註釋。code

方法以下:orm

<!-- lang: java -->
/**
 * Utility method to take a string and convert it to normal Java variable
 * name capitalization.  This normally means converting the first
 * character from upper case to lower case, but in the (unusual) special
 * case when there is more than one character and both the first and
 * second characters are upper case, we leave it alone.
 * <p>
 * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays
 * as "URL".
 *
 * @param  name The string to be decapitalized.
 * @return  The decapitalized version of the string.
 */
public static String decapitalize(String name) {
    if (name == null || name.length() == 0) {
        return name;
    }
    if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
                    Character.isUpperCase(name.charAt(0))){
        return name;
    }
    char chars[] = name.toCharArray();
    chars[0] = Character.toLowerCase(chars[0]);
    return new String(chars);
}

咱們使用這個方法對幾種不一樣的字段名進行測試:ci

看下面的代碼:文檔

<!-- lang: java -->
public class TestBean {
    public static void main(String[] args) {
        System.out.println(Introspector.decapitalize("name"));
        System.out.println(Introspector.decapitalize("Name"));
        System.out.println(Introspector.decapitalize("mName"));
        System.out.println(Introspector.decapitalize("NAME"));
    }
}

輸出:

name
name
mName
NAME

從結果來看nameName的結果是同樣的,也就是說若是字段名是Name,會被當成name使用,所以從這個角度來講這種命名方式是錯誤的,不符合規範的。

mName是沒問題問題的。NAME也沒有問題,NAme,NAMe這樣也不會有錯。

這篇文章說深刻可能還不夠資格,而且標題中的setter和getter根本沒提。若是有不明白的地方,歡迎留言!

相關文章
相關標籤/搜索