Spring ReflectionUtils用于泛型类



我正在使用Spring ReferectionUtils设置一个名为">类型";对于泛型类GenericServiceImpl:

GenericServiceImpl是接口GenericService 的实现

public interface GenericService<T>{ }
public class GenericServiceImpl<T> implements GenericService<T>{
public Class<T> type;
public GenericServiceImpl(Class<T> type){
this.type = Objects.requireNonNull(type);
}
public GenericServiceImpl(){ }
}

我的目的是用泛型类值设置属性类型,我将给您举一个例子:我有两个类型为GenericServicebeanA和beanB的bean,它们分别有两个类A和B作为Generic类型。我有另一个服务类MyService,它注入了后者。

@Service
public class MyService{
private final GenericService<A> beanA;
private final GenericService<B> beanB;
public MyService(GenericService<A> beanA,GenericService<B> beanB){
this.beanA=beanA;
this.beanB=beanB;
}
}

所以我想用A.class设置beanA的属性type,用B.class设置beanB也是如此;

我想通过Java反射API或使用Spring框架来实现后者,这些框架使Refection API的使用更容易。

因此,我在MyService类中添加了一个名为init((的方法,并用@PostConstruct进行了注释。

@PostConstruct
public void init() {
ReflectionUtils.doWithFields(beanA.getClass(),
(Field field) -> {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, beanA, A.class);
},
(Field field) -> field.getType() == Class.class
);
ReflectionUtils.doWithFields(beanB.getClass(),
(Field field) -> {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, beanB, B.class);
},
(Field field) -> field.getType() == Class.class
);
}

但我发现实施方式是混乱的,因为领域">类型";使B.class在两个bean中都具有值:beanA和beanB!!

谢谢你的帮助。

注入MyService的实例应该已经完全设置好了。为什么不做一些类似的事情:

@Configuration
class MyConfig {
@Bean
GenericService<A> aService() {
return new GenericService(A.class);
}
@Bean
GenericService<B> bService() {
return new GenericService(B.class);
}
}

也许你可以更好地解释你试图用类结构实现什么,而不是用这种方式使用它时遇到的特定问题。

最新更新