创建@Autowired注解
package com.zzj.test; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; //设置范围和生存周期
@Target({ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired { }
创建UserInfo并且为添加了@Autowired的成员变量赋值
package com.zzj.test; import java.lang.reflect.Field;
import java.util.Date; //UserInfo类含有两个成员变量
class UserInfo{ @Autowired
private Date birth;
@Autowired
private String name; public Date getBirth() {
return birth;
} public void setBirth(Date birth) {
this.birth = birth;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} } //给有AutoWired注释的成员变量赋值
public class Test { public static void main(String[] args)throws Exception{ Class clazz = UserInfo.class;
//反射创建userinfo对象
Object object = clazz.newInstance();
//获取成员变量
Field[] fields = clazz.getDeclaredFields(); for(Field field: fields){ //获取成员变量上的注释,如果有autowired注释则赋初始值
Autowired autowired = field.getAnnotation(Autowired.class); if(autowired != null){
//获取成员变量的类型
clazz = field.getType();
//调用类型的默认构造方法String是"",Date是当前时间
Object value = clazz.newInstance();
//私有成员变量解锁权限
field.setAccessible(true);
//设置初始值,
field.set(object, value); } } //类型强转,并输出确认结果
UserInfo ui = (UserInfo)object;
System.out.println(ui.getName());
System.out.println(ui.getBirth()); } }
输出结果如下(由于String初始值为""所以第一行为空)