通常,当我们想要获得一个类的对象时,我们会用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( )方法将之前获得的实例化对象传入;