Java內省的使用(續)

     剛纔說了Apache組織結合很多實際開發中的應用場景開發了一套簡單、易用的API操作Bean的屬性——BeanUtils,也給大家顯出了代碼的實現。十分簡單,便捷。

     那麼接下來就讓我們來看看其中的幾個框架,以及其中一些轉換器的使用。

     Person類:

public class Person {
	private int age;
	private String name;
	private Date birth;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	public Person(){
		
	}
}

   測試類:

public class PersonTest {
	@Test
	public void test() throws Exception {
		// 得到class對象
		Class cls = Class.forName("www.csdn.net.beanutils.Person");
		// 實例化對象
		Person bean = (Person) cls.newInstance();

		/**
		 *  BeanUtils框架
		 */
		// 設置值
		BeanUtils.setProperty(bean, "age", "12");// 12本身是字符串,但是在這裏就自動轉換了(如果爲12s,則輸出的是0)
		// 讀取值
		String s = BeanUtils.getProperty(bean, "age");
		System.out.println("獲取利用BeanUtils框架setProperty()設置的值爲:" + s);

		/** PropertyUtils框架
		 * 
		 */
		// 設置值
		PropertyUtils.setProperty(bean, "name", "Retror");
		// PropertyUtils框架
		// 讀取值
		Object value = PropertyUtils.getProperty(bean, "name");
		System.out.println("獲取利用PropertyUtils框架setProperty()設置的值爲:" + value);

		// birth屬性
		
		// 自定義的轉換器
		ConvertUtils.register(new Converter() {

			public Object convert(Class arg0, Object arg1) {
				System.out.println(arg0 + "---" + arg1);
				//類型----字符串
				if (arg1 == null) {//判斷值是否爲空
					return null;
				} else {
					try {
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy年MM月dd日");
						return sdf.parse((String) arg1);
						//parse()方法,從給定字符串的開始解析文本,以生成一個日期。該方法不使用給定字符串的整個文本
					} catch (ParseException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}
			}
		}, Date.class);
		
		//採用內部的轉換器完成的轉換
		//ConvertUtils.register(new DateLocaleConverter(), Date.class);
		
		// 設置屬性
		/**
		 * 自定義轉換器實現
		 */
		//實現
		BeanUtils.setProperty(bean, "birth", "1992年10月10日");
		//BeanUtils.setProperty(bean, "birth", "1992-10-10");
		// 讀取值
		String v = BeanUtils.getProperty(bean, "birth");
		System.out.println(v);
	}
}

 

     效果:


    這裏,在測試類中通過兩個框架(BeanUtils和PropertyUtils)來實現了設置值和讀取值的操作,並且在其中利用自定義的轉換器來實現日期的轉換。希望大家能從中得到一些幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章