javaBean

引用

package com.java.day01;

import java.lang.reflect.Method;

public class BeanUtil {

	//javaBean
	//1,公共无参构造方法;
	//2,属性存取方法符合set-get 规范;
	
	public static void setProperty (
			Object o,String name,Object value) throws Exception{//属性变为set方法;
		String methodName = 
			"set" + name.substring(0,1).toUpperCase()+
					     name.substring(1);
		Method m = null;
		Class paramClass = value.getClass();
		if(paramClass == Integer.class){
			//setAge(Integer),getAge(int)
			try {
				m = o.getClass().getMethod(methodName, new Class[]{value.getClass()});
			} catch (Exception e) {
				m = o.getClass().getMethod(methodName, new Class[]{int.class});
			}
		}else{
			m = o.getClass().getMethod(methodName, new Class[]{int.class});
		}
		m.invoke(o, new Object[]{value});
	}
	
	public static Object getProperty(Object o,String name) throws Exception{
		String methodName = 
			"get" + name.substring(0,1).toUpperCase()+
					     name.substring(1);
		Method m = o.getClass().getMethod(methodName, null);
		return m.invoke(o, null);
	}
	public static void main(String[] args) throws Exception{
		Student stu = new Student();
		setProperty(stu, "age", 23);
		System.out.println(stu.getAge());
	}
}
class Student{
	private String name;
	private int age;
	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;
	}
	
	
}

你可能感兴趣的:(javabean)