我们知道spring技术的基本原理就是基础反射机制,那么到底什么是反射呢?下面是我啃书的一些收获,不知道理解是否正确
java的反射机制能够实现配置很多内容,比如:类的全限定名 方法 参数,完成对象的初始化.
反射是通过java.lang.reflect.* 实现的
通过反射来构建对象:
首先创建一个类(默认无参构造)
public class ReflectServiceImpl {
public void sayHello(String name) {
System.err.println("Hello " + name);
}
}
通过反射方法去构建它
public ReflectServiceImpl getInstance() {
ReflectServiceImpl object = null;
try {
object = (ReflectServiceImpl) Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl")
.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
ex.printStackTrace();
}
return object;
}
创建一个类(有参构造)
public class ReflectServiceImpl2 {
private String name;
public ReflectServiceImpl2(String name) {
this.name = name;
}
}
String name) {
this.name = name;
}
}
不能使用之前的反射方法进行构造了
public ReflectServiceImpl2 getInstance() {
ReflectServiceImpl2 object = null;
try {
object =
(ReflectServiceImpl2)
Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl2").
getConstructor(String.class).newInstance("张三");
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | NoSuchMethodException
| SecurityException | IllegalArgumentException
| InvocationTargetException ex) {
ex.printStackTrace();
}
return object;
}
getConstructor(String.class).newInstance("张三");
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | NoSuchMethodException
| SecurityException | IllegalArgumentException
| InvocationTargetException ex) {
ex.printStackTrace();
}
return object;
}
先通过forName加载到类的加载器,然后再用getConstructor方法,参数可以有多个,这里定义为String.class,意为只有一个参数类型为String的构造方法.
放射的有点就是能通过配置实现对象的创建,解除程序的耦合度. 反射的缺点是运行的速度慢.
反射对象方法
在使用方法之前首先要获得方法的对象
public Object reflectMethod() {
Object returnObj = null;
ReflectServiceImpl target = new ReflectServiceImpl();
try {
Method method = ReflectServiceImpl.class.getMethod("sayHello", String.class);
returnObj = method.invoke(target, "张三");
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException| InvocationTargetException ex) {ex.printStackTrace();}return returnObj;}
当有具体的target但是不知道属于哪个类时,也可以使用
target.getClass().getMethod("sayHello",String.class);
多个参数可以编写多个类型,这样可以获得反射方法的对象. 反射方法
Method method = ReflectServiceImpl.class.getMethod("sayHello", String.class);
这样就可以获得反射方法.
returnObj = method.invoke(target, "张三");
等同于target.sayHello("张三").
这样下来,我们就对spring的配置原理可能就有一些了解了,通过配置实现方法的调用和对象的创建.