java反射在spring中的应用

   1.为什么要用反射?

    根据对象可以得到该类的所有信息,可以做直接操作对象不能做的事,它不是在编译时执行,而是在运行时执行,也就是执行.class时执行,所以它可以做在编译时不能做的事,像hibernate的属性映射就是通过反射来赋值的,spring的bean的创建就是根据配置的class来反射构建的


  2.反射怎么用

     我就不像网上说一大堆理论知识了,直接写个spring注入的例子

    

<span style="font-size:18px;">public class ReflectDemo
{
    public static void main(String[] args)
    {

        try
        {
            String classPath = "com.chenjun.Compute";// 由spring中bean 的class属性值传进来

            Class class1 = Class.forName(classPath); // 这是获得class对象最常用的方式,还有.class,getClass()两种方式

            Object object = class1.newInstance();

            String attrName = "a";// 代表spring中待注入的属性
            String attrValue = "hello";// 代表spring中待注入的属性值
            Method method = class1.getMethod("set" + attrName.toUpperCase(), String.class);
            method.invoke(object, attrValue);// 调用setter方法为bean注入属性值

            System.out.println(object.toString());

        }
        catch (SecurityException e)
        {
            e.printStackTrace();
        }

        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

class Compute
{

    private String a;

    public String getA()
    {
        return a;
    }

    public void setA(String a)
    {
        this.a = a;
    }

    @Override
    public String toString()
    {
        return a;
    }

}</span>

输出:hello,说明注入成功,这个class对应的bean也就创建成功



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值