我正在使用Spring为泛型类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(){ }
}
我的目的是用泛型类值设置属性类型,我将给出一个示例:我有两个类型为GenericService beanA和beanB的beanB,它们分别有两个类A和B作为泛型类型。我有另一个服务类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;
}
}
因此,我希望设置属性类型 of beanA,并将A.class设置为值,对于beanB和B.class设置相同;
我希望通过Java反射API或使用Spring框架来实现后者,这些框架使反射API的使用更加容易。
因此,我在@PostConstruct MyService类中添加了一个名为init()的方法。
@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
);
}
但是我发现实现的方式很混乱,因为“类型”字段在beanB中都有B.class值: beanA和beanB!
谢谢你的帮助。
发布于 2022-07-27 11:36:47
注入到MyService
中的实例应该已经完全设置了。为什么不做这样的事情:
@Configuration
class MyConfig {
@Bean
GenericService<A> aService() {
return new GenericService(A.class);
}
@Bean
GenericService<B> bService() {
return new GenericService(B.class);
}
}
也许你可以用你的类结构来更好地解释你想要达到的目标,而不是用这种方式来解决特定的问题。
https://stackoverflow.com/questions/73136863
复制相似问题