java 反射

本文介绍了Java反射机制的基本概念及其应用场景,通过对比new关键字实例化类的方式,详细解释了如何使用反射来动态创建对象并调用其方法,适用于编译时未知类的情况。

通常,当我们想要获得一个类的对象时,我们会用new关键字实例化一个类。而java反射为我们提供了另一种方法。
假如我们在编译时无法确定对象与类的归属,只能依靠运行时来发现,此时我们需要用到反射。
反射实现了松耦合。
spring 使用了反射。
下面,我们分别用new 关键字和反射来演示:
new关键字:

        URL url = new URL("http://baidu.com");
        String host = url.getHost();
        System.out.println(host);

反射:

//用java 的反射机制 实现相同内容
        Class<?> type =Class.forName("java.net.URL");
        //获得URL 类的带参类型为String 的构造函数
        Constructor<?> constructor = type.getConstructor(String.class);
        //获得 类的实例
        Object instance = constructor.newInstance("http://baidu.com");

        Method method = type.getMethod("getHost");
        Object methodCallRestult = method.invoke(instance);
        System.out.println(methodCallRestult);

几个重要方法

1 newInstance( ) 查看api文档:
public T newInstance(Object… initargs)

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor’s declaring class, with the specified initialization parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.

使用这个构造函数对象所表示的构造函数来创建和初始化构造函数的声明类的新实例,并使用指定的初始化参数;
即,使用之前用getConstructor( )返回的构造函数来实例化一个类对象。

2 mothod.invoke( ) api文档:
public Object invoke(Object obj,Object… args)
Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.
调用由该方法对象所表示的底层方法,在指定的对象上使用指定的参数。
在调用mothod.invoke( )方法之前,我们用type.getMethod(“getHost”);获得类所要使用的函数名,然后用mothod.invoke( )方法将之前获得的实例化对象传入;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值