1、我们来体验一下Spring底层两大思想中IOC(Inverse Of Control)
2、IOC控制反转主要利用的就是Java强大的反射机制
这里并没有写数据层,有兴趣的同学可以通过流的方式,来创建我们需要的对象
1)创建一个testreflect的包,然后写MockSpring类的方法getBean
package testreflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Scanner;
public class MockSpring {
public Object getBean (String className) {
Object obj = null;
Scanner input = new Scanner(System.in);
try{
//获取类
Class clazz = Class.forName(className);
//获取对象
obj = clazz.newInstance();
String name = clazz.getSimpleName();
if(name.equals("Character")){
System.out.println("Incompatible Type.");
}else{
Field[] fields = clazz.getDeclaredFields();
for(Field f:fields){
String fieldName = f.getName();
System.out.println("请设置"+fieldName+"属性:");
//获取setName类似的驼峰属性设置方法
StringBuilder sb = new StringBuilder("set");
sb.append(fieldName.substring(0,1).toUpperCase().concat(fieldName.substring(1)));
String value = input.nextLine();
//获取属性的类型,比如name的String类
Class fieldType = f.getType();
//获取带String参数的构造函数
Constructor con = fieldType.getConstructor(String.class);
//获取方法
Method m = clazz.getDeclaredMethod(sb.toString(),fieldType);
m.setAccessible(true);
m.invoke(obj,con.newInstance(value));
}
}
}catch(Exception e){
e.printStackTrace();
}
return obj;
}
}
2)创建一个测试类
注意:要有set方法,我们的目的是以后从文件读取的流能直接转为对象
package testreflect;
public class Person {
private String name;
private Integer age;
private String sex;
public Person () {}
public Person (String name,Integer age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public void setName (String name){
this.name = name;
}
public void setAge (Integer age){
this.age = age;
}
public void setSex (String sex){
this.sex = sex;
}
public String getName (){
return this.name;
}
}
3)测试
package testreflect;
public class Test {
public static void main (String[] args){
MockSpring ms = new MockSpring();
Person p = (Person)ms.getBean("testreflect.Person");
System.out.println(p.getName());
}
}
4)根据提示设置name,age,sex属性为"飞鸿","18","男"
output:飞鸿