[英]How to improve Java generics wildcard signature
I'm trying to create DI container get
method, but struggling with signature. 我正在尝试创建DI容器get
方法,但努力与签名。 Currently I have this definition: 目前我有这个定义:
public Object get(Class<?> key) {
// returns instance of `?`
}
The part of my code which I dont like much is usage of the get
method: 我不喜欢的代码部分是get
方法的用法:
IRouter router = (IRouter) container.get(IRouter.class);
where I have to cast return with (IRouter)
. 在哪里我必须使用(IRouter)
。 Any ideas how to change method signature to make usage like this? 任何想法如何改变方法签名以使这样的用法?
IRouter router = container.get(IRouter.class);
Thanks in advance for any ideas! 提前感谢任何想法!
By using a scoped method parameterized type : 通过使用作用域方法参数化类型:
public <T> T get(Class<T> key) {
// ...
return (T) foo;
}
Here I suppose that foo
is not typed as T
. 这里我假设foo
没有输入T
If it is already typed as T
you can of course return it without cast. 如果它已经被输入为T
你当然可以在没有强制转换的情况下返回它。
You could so invoke it : 你可以调用它:
IRouter router = container.get(IRouter.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.