描述
您可以使用以下方式訪問基本屬性:
簡單屬性
索引屬性
映射屬性
簡單屬性
您可以獲取并設置簡單使用以下API簽名的屬性值:
PropertyUtils.getSimpleProperty(Object,String)
PropertyUtils.SetSimpleProperty(Object,String,Object)
參數:
對象:它是一個bean對象,用于指定要提取的bean屬性.
字符串:它是一個字符串名稱,用于指定要提取的屬性的名稱./p>
索引屬性
您可以使用兩個選項來創建索引屬性;第一個選項是將下標構建到屬性名稱中,第二個選項是在單獨的參數中定義下標以調用方法.
索引屬性可以通過使用來獲取和設置以下方法:
PropertyUtils.getIndexedProperty(Object,String)
PropertyUtils.getIndexedProperty(Object,String,int)
PropertyUtils.setIndexedProperty(Object,String,Object)
PropertyUtils.setIndexedProperty(Object,String,int,Object)
參數:
對象:這是一個bean對象,它指定bean屬性為提取.
字符串:這是一個字符串名稱,用于指定要提取的屬性的名稱.
int :它設置屬性值的索引.
Object :它指定索引屬性elem的值ent.
映射屬性
您可以獲取并設置使用以下API簽名映射屬性值.如果你有任何額外的參數,那么它可以在括號內寫成("("和")")而不是使用方括號.
PropertyUtils.getMappedProperty(Object,String)
PropertyUtils.getMappedProperty(Object,String,String)
PropertyUtils.setMappedProperty(Object,String,Object)
PropertyUtils.setMappedProperty(Object,String, String,Object)
參數:
對象:它是一個bean對象,它指定要提取的bean屬性.
String :它是應為Mapped屬性設置的屬性值的名稱.
String :它定義要設置的屬性值的鍵.
對象:它指定要設置的屬性的值.
示例
以下示例演示使用o f以上beanUtils中的屬性:
import org.apache.commons.beanutils.PropertyUtils;import java.util.ArrayList;import java.util.List;public class BeanUtilsPropertyDemo{ public static void main(String args[]){ try{ // Creating the bean and allows to access getter and setter properties MyBean myBean = new MyBean(); // Setting the properties on the myBean PropertyUtils.setSimpleProperty(myBean, "stringProp", "Hello!This is a string"); PropertyUtils.setSimpleProperty(myBean, "floatProp", new Float(25.20)); // Getting the simple properties System.out.println("String Property: " + PropertyUtils.getSimpleProperty(myBean, "stringProp")); System.out.println("Float Property: " + PropertyUtils.getSimpleProperty(myBean, "floatProp")); // Here we will create a list for the indexed property Listlist = new ArrayList(); list.add("String value 0"); list.add("String value 1"); myBean.setListProp(list); // get and set this indexed property PropertyUtils.setIndexedProperty(myBean, "listProp[1]", "This is new string value 1"); System.out.println("List Property[1]: " + PropertyUtils.getIndexedProperty(myBean, "listProp[1]")); }catch(Exception e){ System.out.println(e); } }}
現在我們將再創建一個名為 MyBean的類.用于bean類的java :
import java.util.ArrayList;import java.util.List;public class MyBean { private String stringProp; private float floatProp; //indexed property @SuppressWarnings("rawtypes") private List listProp = new ArrayList(); public void setStringProp(String stringProp) { this.stringProp = stringProp; } public String getStringProp() { return this.stringProp; } public void setFloatProp(float floatProp) { this.floatProp = floatProp; } public float getFloatProp() { return this.floatProp; } public void setListProp(List<?> listProp) { this.listProp = listProp; } public List<?> getListProp() { return this.listProp; }}
輸出
讓我們執行以下步驟來看看上面的方法代碼有效:
將上面的第一個代碼保存為 BeanUtilsPropertyDemo.java .
現在使用"運行"選項或Ctrl + f11執行代碼并顯示如下輸出.
免責聲明:以上內容(如有圖片或視頻亦包括在內)有轉載其他網站資源,如有侵權請聯系刪除