2013-02-14 64 views
1

我嘗試使用setter來設置值,但null會出現。請幫助我解決此問題,並告訴我是否還有其他更好的方法。使用BeanUtils設置設置值

import org.apache.commons.beanutils.BeanUtils; 

public class TestSetter { 

    public static void main(String args[]) throws Exception 
    { 
     Test t = new Test(); 
     BeanUtils.setProperty(t,"te","teval"); 
     System.out.println("tevalue :"+t.getTe()); 
    } 
} 
class Test 
{ 
    String te; 

    public String getTe() { 
     return te; 
    } 

    public void setTe(String te) { 
     this.te = te; 
    } 

} 

例外:

Exception in thread "main" java.lang.reflect.InvocationTargetException: Cannot set te 
    at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1025) 
    at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:313) 
    at test.reflection.TestSetter.main(TestSetter.java:10) 
Caused by: java.lang.NoSuchMethodException: Property 'te' has no setter method 
    at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1746) 
    at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648) 
    at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677) 
    at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1022) 
    ... 2 more 
+1

不能讓我經驗領域,但嘗試'BeanUtils.setProperty(t,「Te」,「teval」)'代替... – MadProgrammer 2013-02-14 04:11:53

+0

對不起,因爲這也給出了相同的結果。 – sunleo 2013-02-14 04:12:56

回答

12

您的等級Test應該是public類,將Test移動到一個自己的文件,使其公開並重新運行您的代碼。

+0

謝謝你的作品問題是它缺少的公共修飾符。 – sunleo 2013-02-14 04:19:26

+1

+1好收拾 – MadProgrammer 2013-02-14 04:21:26

6

其設於字段的名稱:

BeanUtils.setProperty(t,"te","teval"); 

Documentation這裏

+0

已經試過了,它給了這個異常引起:java.lang.NoSuchMethodException:屬性'te'沒有setter方法 – sunleo 2013-02-14 04:11:50

+0

Doc說,但它不工作多數民衆贊成在爲什麼問..... – sunleo 2013-02-14 04:15:25

+0

測試類不是上市。 BeanUtils似乎不能解析受保護的類...(ps否則是正確的) – MadProgrammer 2013-02-14 04:19:58

0

setProperty()

的方法簽名210
public static void setProperty(Object bean, 
           String name, 
           Object value) 
         throws IllegalAccessException, 
           InvocationTargetException 

    Parameters: 
     bean - Bean on which setting is to be performed 
     name - Property name (can be nested/indexed/mapped/combo) 
     value - Value to be set 

name是屬性名稱「te」不是「setTe」。

BeanUtils.setProperty(t,「te」,「teval」);

+0

我接受和測試,但現在它給這個錯誤。我更新了問題。請檢查。 – sunleo 2013-02-14 04:17:31

+0

@sunleo測試課程不公開,請參閱Jayamohan的答案,然後申請Shawn和Pradeep的答案 – MadProgrammer 2013-02-14 04:21:10