其实spring是基于java的反射机制,现在举个示例看一下:
比如有个User类
public class User {
String userName;
String password;
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/*
* 打印用户信息
*/
public void printInfo(){
System.out.println("userName:"+userName+",password:"+password);
}
}
然后我们再写一个类对其进行反射
import java.lang.reflect.Method;
public class Reflect {
public static void main(String[] args) {
try{
//根据类名(spring中是从applicationContext.xml中读取的)获得其类,注意这时还不是实例,只是个类
Class<?> objClass=Class.forName("User");
/*
* 由类获取setter方法(spring中是从applicationContext.xml中读取的)
* 第一个参数据是方法名,第二个是方法的参数(这里这用的是String类),可以是数组表示多个参数
*/
Method setNameMethod=objClass.getMethod("setUserName", String.class);
Method setPasswordMethod=objClass.getMethod("setPassword", String.class);
//有的方法是private,设置方法的访问属性为可访问
setNameMethod.setAccessible(true);
setPasswordMethod.setAccessible(true);
//实例化对象
Object obj=objClass.newInstance();
//调用方法进行注入
setNameMethod.invoke(obj, new String("shirui"));
setPasswordMethod.invoke(obj, new String("0000"));
//此时完成注入,我们进行测一下
User user=(User)obj;//spring中是ctx.getBean("user");
user.printInfo();
/*
* 到此完成spring底层的反射机制
*/
}catch(Exception e){
e.printStackTrace();
}
}
}