zoukankan      html  css  js  c++  java
  • 使用内省的方式操作JavaBean

    import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    /**
     * 使用内省的方式操作JavaBean
     */
    public class IntroSpectorTest {
    
    	public static void main(String[] args) throws Exception {
    		ReflectPoint reflectPoint = new ReflectPoint(3,7);
    		
    		//调用JavaBean中方法的传统作法
    		Class classz = reflectPoint.getClass();
    		Field[] fields = classz.getDeclaredFields();
    		for (Field field : fields) {
    			String name = "set" + field.getName().toUpperCase();
    			Method method = classz.getMethod(name, int.class);
    			method.invoke(reflectPoint, 3);
    		}
    		System.out.println(reflectPoint);
    		
    		//使用内省的方式调用JavaBean的方法
    		String propertyName = "x";
    		//获得属性x的值
    		Object retVal = getProperty2(reflectPoint, propertyName);
    		System.out.println(retVal);
    		//设置属性x的值
    		setProperty(reflectPoint, propertyName,10);
    		System.out.println(reflectPoint.getX());
    		
    	}
    
    	/**
    	 * 设置属性的值
    	 * @param obj 属性所属的对象
    	 * @param propertyName 属性名
    	 * @param propertyValue 属性值
    	 */
    	private static void setProperty(Object obj, String propertyName,Object propertyValue) throws Exception {
    		PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,obj.getClass());
    		Method setMethod = pd2.getWriteMethod();
    		setMethod.invoke(obj, propertyValue);
    	}
    
    	/**
    	 * 获得对象的属性值
    	 * @param obj 属性所属的对象
    	 * @param propertyName 属性名
    	 * @return 属性的值
    	 */
    	private static Object getProperty(Object obj, String propertyName) throws Exception {
    		PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass());
    		Method getMethod = pd.getReadMethod();	//获得get方法
    		Object retVal = getMethod.invoke(obj);
    		return retVal;
    	}
    	
    	/**
    	 * 使用内省操作javabean
    	 * @param obj 属性所属的对象
    	 * @param propertyName 属性名
    	 * @return 属性的值
    	 */
    	private static Object getProperty2(Object obj, String propertyName) throws Exception {
    		Object retVal = null;
    		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
    		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    		for (PropertyDescriptor pd : pds) {
    			if (pd.getName().equals(propertyName)) {
    				Method getMethod = pd.getReadMethod();
    				retVal = getMethod.invoke(obj);
    				break;
    			}
    		}
    		return retVal;
    	}
    }
    

  • 相关阅读:
    python函数及模块
    Python分支结构及循环结构
    python基本的知识
    11.21学习总结
    进度日报28
    进度日报27
    进度日报26
    进度日报25
    进度日报24
    11.14学习总结
  • 原文地址:https://www.cnblogs.com/xyang0917/p/4172545.html
Copyright © 2011-2022 走看看