用反射方法的優(yōu)點(diǎn):
代碼簡(jiǎn)潔,不需要有什么配置Model屬性有變化時(shí)不必再手動(dòng)更改toString方法缺點(diǎn):
有些屬性并不想讓輸出來(lái)(可能沒(méi)用,也可能出于安全方面考慮),但是反射時(shí)所有的屬性值都給輸出來(lái)
安全方面的考慮. 一般來(lái)說(shuō),一個(gè)java類(lèi)是的屬性都是PRivate的,這樣用反射來(lái)構(gòu)建toString方法時(shí),就得繞過(guò)private的限制. 于是 If your system is running under a restrictive SecurityManager , you may need to alter your configuration to allow Commons Lang to bypass these security restrictions.
彌補(bǔ)用反射方法不夠靈活的一個(gè)擴(kuò)展. 由假設(shè)一個(gè)類(lèi)里有名為passWord這樣的屬性,一般情況下,是不想讓toString輸入的, 但用反射默認(rèn)情況下是會(huì)輸出的. 這怎么辦呢?看ReflectionToStringBuilder源碼里文檔時(shí),發(fā)現(xiàn)這么一個(gè)擴(kuò)展: 通過(guò)子類(lèi),覆蓋其accept方法來(lái)加以篩選.具體如下所示:
public String toString() { return (new ReflectionToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) {// 注意這里為了表達(dá)上的簡(jiǎn)潔用了匿名內(nèi)部類(lèi). protected boolean accept(Field f) { return super.accept(f) && !f.getName().equals("password"); } }).toString();}這樣在toString時(shí), 就會(huì)跳過(guò)名為password的屬性.
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注