类型带反射的文字注入
上下文:java使用guice(最新版本)
大家好,是否可以通过这种方式用Guice注入一些TypeLiteral:
public MyClass<?,?> getMyClass(Injector injector, Class<?> a, Class<?> b)
{
//how to Inject MyClass with type a & b ?
//e.g : injector.getInstance(MyClass<"a class","b class">)
}
public interface MyClass<S,T>
{
public T do(S s);
}
public class ClassOne implements MyClass<String,Integer>
{
public Integer do(String s)
{
//do something
}
}
Module :
bind.(new TypeLiteral<MyClass<String,Integer>(){}).to(ClassOne.class);
bind.(new TypeLiteral<MyClass<String,Double>(){}).to(ClassTwo.class);
...
处理这个问题的最佳方法是什么(使用吉斯)?
谢谢 !
Context : java using guice (last version)
Hi everybody, is it possible to inject some TypeLiteral with Guice by this way :
public MyClass<?,?> getMyClass(Injector injector, Class<?> a, Class<?> b)
{
//how to Inject MyClass with type a & b ?
//e.g : injector.getInstance(MyClass<"a class","b class">)
}
public interface MyClass<S,T>
{
public T do(S s);
}
public class ClassOne implements MyClass<String,Integer>
{
public Integer do(String s)
{
//do something
}
}
Module :
bind.(new TypeLiteral<MyClass<String,Integer>(){}).to(ClassOne.class);
bind.(new TypeLiteral<MyClass<String,Double>(){}).to(ClassTwo.class);
...
What is the best way to handle this problem (with Guice)?
Thank you !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为您的类型创建一个 ParameterizeType :
从中创建一个 TypeLiteral :
现在创建注入实例:
实际上,您想自己实现 ParameteriedType :
编辑:事实上,您可以使用:
参见 带有类型参数的 Guice 模块
Create a ParameterizeType for your type :
Create a TypeLiteral from it:
Now create injected instance:
In practice you want to implement the ParameteriedType yourself:
EDIT: In fact, you can use:
see Guice module with type parameters
事实上,我认为这是不可能的。泛型在运行时并未具体化。这意味着该信息在运行时不存在。所以它并不关心你给它什么泛型类型。
所以,我认为这个方法是没有必要的。简单来说就是这样:
由于
MyClass
是一个接口,所以你想要实现的东西是完全无用且不可能的。当您只指定参数类型和返回类型时,您希望如何实例化具有特定行为的对象。我认为你应该尝试寻找一种不同的工作方式。
In fact, I think it isn't possible. Generics are not reified at run-time. This means the information is not present at run-time. So it doesn't care what generic type you give it.
So, I think this method is not needed. Simply something like this:
Since
MyClass
is an interface, what you want to achieve is totally useless and impossible. How do you want to instantiate an object with a specific behavior when you only specify the param type and return type.I think you should try to find a different way of working.