得到子类反射泛型,以及如何通过注解注入对象(仅供参考,未写实例代码)

//哪个子类调的这个方法,得到的class就是子类处理的类型(非常重要)

//
public BaseDao(){
Class clazz = this.getClass();  //拿到的是子类   这里非常的重要    
ParameterizedType  pt = (ParameterizedType) clazz.getGenericSuperclass();  //BaseDao<Category>  //反射范型
clazz = (Class) pt.getActualTypeArguments()[0];
System.out.println(clazz);
}





//如何通过注解来为person注入一个对象
//1.得到需要注入的属性
Field f = PersonDao.class.getDeclaredField("person");

//2.得到属性需要的 类型
Class clazz = f.getType();

//3.创建person
Person person = (Person) clazz.newInstance();

//4.反射属性的注解,
InjectPerson inject = f.getAnnotation(InjectPerson.class);

//5.并用注解的信息填充person
Method ms [] = inject.getClass().getMethods();
for(Method m : ms){
String methodName = m.getName();  //name( ) age()
//看person对象上有没有注解与之对应的属性
try{
Field f = Person.class.getDeclaredField(methodName);
f.setAccessible(true);
f.set(person,m.invoke(inject, null))
PropertyDescriptor pd = new PropertyDescriptor(methodName,Person.class);
Method set = pd.getWriteMethod();  //setname setage
set.invoke(person, m.invoke(inject, null));
}catch (Exception e) {
continue;
}
}

//6.把person赋给dao
PersonDao dao = new PersonDao();
f.setAccessible(true);  //person
f.set(dao, person);



//这里是反射方法上面的代码

//1.得到要注入的属性
PropertyDescriptor pd = new PropertyDescriptor("person",PersonDao.class);

//2.得到要注入的属性需要的类型
Class clazz = pd.getPropertyType();  //Person

//3.创健属性需要的对象
Object person = clazz.newInstance();

//4.得到属性的写方法
Method setPerosn = pd.getWriteMethod();

//5.反射出方法上声明的注解
InjectPerson inject = setPerosn.getAnnotation(InjectPerson.class);

//6.得到注解上声明的信息,填充person对象
Method[] methods = inject.getClass().getMethods();
for(Method m : methods){
String methodName = m.getName();  //name or age
try{
Field f = Person.class.getDeclaredField(methodName);
Object value = m.invoke(inject, null);  //得到注解上配置的属性的值
f.setAccessible(true);
f.set(person, value);
}catch (Exception e) {
continue;
}

}


//7.把填充了数据的person通过setPerson方法整到personDao对象上
PersonDao dao = new PersonDao();
setPerosn.invoke(dao, person);

System.out.println(dao.getPerson().getName());



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值