定义一个注解用于放在属性上面给属性赋值
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
String value();
}
定义工具方法,根据提供的类全名以及类属性上注解上的值将对象创建出来(这个工具这里只能处理属性为基本数据类型的自动注入。仅仅当作一个练习)
public class IocTestUtil {
public static <T>T getBean(String className){
try {
//加载类
Class clazz = Class.forName(className);
//创建类对象
T obj = (T)clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields){
//找到属性对应的set方法名
StringBuilder setMethodName = new StringBuilder("set");
//找到属性名
String fieldName = field.getName();
//拼接属性对应的方法名 set + 属性名(第一个字母变大写)
String begin = fieldName.substring(0,1).toUpperCase();
String other = fieldName.substring(1,fieldName.length());
setMethodName.append(begin.concat(other));
//找到对应set方法
Method method = clazz.getMethod(setMethodName.toString(),field.getType());
//获取属性上注解的值
Property property = field.getAnnotation(Property.class);
String value = (String) property.getClass().getMethod("value").invoke(property);
//执行方法
method.invoke(obj,field.getType().getConstructor(String.class).newInstance(value));
}
return obj;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
测试类
public class Person {
@Property("哩憨憨")
private String name;
@Property("18")
private Integer age;
@Property("男")
private String sex;
@Property("19912345678")
private String phoneNum;
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 void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", phoneNum='" + phoneNum + '\'' +
'}';
}
}
测试
public class TestMain {
public static void main(String[] args) {
Person person = IocTestUtil.getBean("ioc.Person");
System.out.println(person);
}
}
测试结果