如何与在 Guice 中使用注释值的提供者绑定? [英] How to bind with provider which uses annotation value in Guice?
问题描述
有没有什么方法可以与提供者绑定,在 Google Guice 中解释目标的注释值?
Is there any way to bind with provider which interprets target's annotation value in Google Guice?
例子:
bind(Resource.class)
.annotatedWith(MyAnnotation.class)
.toProvider(new MyProvider<MyAnnotation, Resource>{
public Resource get(MyAnnotation anno){
return resolveResourceByAnnoValue(anno.value());
}
});
我想通过注解绑定来初始化一个 Android Activity 类的字段.它应该必须通过它的唯一 ID 来获取多个资源.
I want to initialize field of an Android Activity class by annotated binding. It should have to take multiple resources by it's unique Id.
原路:
public class TestActivity extends Activity{
private TextView textView;
private Button testButton;
public void onAfterCreate(...){
// set UI declaration resource.
setContentView(R.layout.activity_test);
// initialize fields, it must be done after setting ui definition.
textView = (TextView) findViewById(R.id.textView);
.... initialize other fields, hook them...
...
}
我想以声明的方式绑定 UI 和它的字段,而不是务实地喜欢上面:
I want to bind UI and it's field in declarative way, not pragmatically likes above:
@ResourceID(R.layout.activity_test)
public class TestActivity extends InjectiveActivity{
@ResourceID(R.id.textView) // Auto generated static resource id constant
private TextView textView;
@ResourceID(R.id.testButton)
private Button testButton;
...
}
推荐答案
这是不可能的.
如果 @MyAnnotation
是一个绑定注解,它将使用它的 equals
方法进行比较.@MyAnnotation(5) Resource
将绑定到 @MyAnnotation(5) Resource
,与 @MyAnnotation(6) Resource<相比根本不匹配/代码>.查看this SO answer了解更多信息.与该答案一样,您可以遍历可能的注释值并单独绑定每个注释值,如果您愿意的话.
If @MyAnnotation
is a binding annotation, it will be compared using its equals
method. @MyAnnotation(5) Resource
will be bound to @MyAnnotation(5) Resource
, and that will not match at all compared to @MyAnnotation(6) Resource
. Check out this SO answer for more. As in that answer, you could loop through your possible annotation values and bind each one individually, if you feel like it.
如果 @MyAnnotation
不是绑定注解,您将根本无法从您的提供程序访问它.如 this SO answer 中所述,它是一个被拒绝的功能,将注入站点信息添加到提供程序或依赖项本身.
If @MyAnnotation
isn't a binding annotation, you won't be able to access it at all from your provider. As mentioned in this SO answer, it is a rejected feature to add injection-site information to the provider or dependency itself.
最好的办法是创建 @Assisted
注入(或手动工厂)接受参数:
Your best bet is to create an @Assisted
injection (or manual factory) to accept the parameter:
class MyConsumer {
final Resource resource;
@Inject MyConsumer(Resource.Factory resourceFactory) {
int previouslyAnnotatedValue = 5;
this.resource = resourceFactory.createWithValue(previouslyAnnotatedValue);
}
}
您也可以考虑使用 自定义注入,它可以让您使用任意注释除了@Inject
,它可以使用你想要的运行时注释值.
You may also consider using Custom Injections, which will let you use an arbitrary annotation other than @Inject
, which may use runtime annotation values however you'd like.
这篇关于如何与在 Guice 中使用注释值的提供者绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!