bean注入demo

public class TestUser {
	
public static void main(String args [] ) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
                Class bean = null;
		try {
			bean = Class.forName("inject.User");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("can't find class");
			e.printStackTrace();
		}  
		BeanInfo info = null;
		try {
			info = Introspector.getBeanInfo(bean);
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			System.out.println("get the information of the class");
			e.printStackTrace();
		}
		// 遍历指定类的方法
		MethodDescriptor[] methods = info.getMethodDescriptors();  
        for (int i = 0; i < methods.length; i++) {  
            System.out.println("方法:"+methods[i].getDisplayName());  
        }  
        // 遍历指定类的属性  
        PropertyDescriptor[] propertys = info.getPropertyDescriptors();  
        for (int j = 0; j < propertys.length; j++) {  
            System.out.println("属性:"+propertys[j].getName());  
        }  
        
        Object obj = bean.newInstance();
        Method mSet = null;  
        for(int k = 0; k < propertys.length; k++){
        	mSet = propertys[k].getWriteMethod();
        	if(propertys[k].getName().equalsIgnoreCase("name")){
        		mSet.invoke(obj, "mutou");
        		continue;
        	}
        	if(propertys[k].getName().equalsIgnoreCase("password")){
        		mSet.invoke(obj, "mutou_password");
        		continue;
        	}
        }
        User user = (User)obj;
        System.out.println(user.getName());
        System.out.println(user.getPassword());   
	}
}
<pre name="code" class="java">public class User {
	
	String name;
	
	String password;
    //setter getter no paragram constructor
}
 

输出

方法:notify
方法:wait
方法:setPassword
方法:getClass
方法:getName
属性:class
属性:name
属性:password
mutou
mutou_password


参考资料 http://blog.csdn.net/zhikun518/article/details/7185499

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值