Ognl訪問對象屬性

來源:互聯網
上載者:User
package com.xs;import ognl.OgnlException;public class OgnlAccess {/** * @param args * @throws OgnlException  */public static void main(String[] args) throws OgnlException {Field field = new Field();System.out.println(ognl.Ognl.getValue("publicField", field));System.out.println(ognl.Ognl.getValue("privateField", field));}}class Field{public int publicField = 10;private int privateField = 11;}

輸出:

10
Exception in thread "main" ognl.NoSuchPropertyException: com.xs.Field.privateField
    at ognl.ObjectPropertyAccessor.getProperty(ObjectPropertyAccessor.java:151)
    at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2210)
    at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:494)
    at ognl.Ognl.getValue(Ognl.java:644)
    at ognl.Ognl.getValue(Ognl.java:702)
    at ognl.Ognl.getValue(Ognl.java:672)
    at com.xs.OgnlAccess.main(OgnlAccess.java:14)

可以看到 publicField欄位正常輸出,privateField報錯。可見有存取權限的欄位,無需getter方法,Ognl找不到getter方法會去直接存取欄位;對於沒有存取權限的欄位則不能直接存取。

給privateField添加getter方法:

class Field{public int publicField = 10;private int privateField = 11;public int getPrivateField() {return privateField;}}

輸出:

10
11

訪問都正常了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.