微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在运行时使用通用类型参数自动装配 Bean

如何解决在运行时使用通用类型参数自动装配 Bean

是的,所以我已经为此纠结了一段时间,希望得到一些建议。

我有一个 Bar 类,其中包含一个我需要连接的类型参数

@Component
@requiredArgsConstructor
@Scope(value = "prototype")
public class Bar<T> extends Foo<T> {

private final Utility utility;

public Bar<T> init(String a,int b) {
    //initializations
}

//some more methods

}

在我看来,我可以像这样使用 ApplicationContext 连接类,

Foo<Detail> foo = applicationContext.getBean(Bar.class).init(a,b);

但这会引发警告,

Type safety: The expression of type Bar needs unchecked conversion to conform to Foo<Detail>.

现在我明白这个问题是因为我在使用 Bar 初始化 ApplicationContext 类的 bean 时没有提到类型参数。

Question is,what might be the right Syntax to mention the typed parameter <Detail> in the above statement?

解决方法

我猜是这样的:

String [] names = context.getBeanNamesForType(ResolvableType.forClassWithGenerics(Bar.class,Detail.class));
Foo<Detail> bar = context.getBean(names[0]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。