如何将特定参数绑定到自定义注释的实例? [英] How do I bind a specific parameter to an instance of a custom annotation?

查看:91
本文介绍了如何将特定参数绑定到自定义注释的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Guice进行以下工作?

How do I make the following work using Guice?

// The Guice Module configuration
void configure() {
  // The following won't compile because HelpTopicId is abstract.
  // What do I do instead?
  bind(new TypeLiteral<String>(){}).
      annotatedWith(new HelpTopicId("A")).toInstance("1");
  bind(new TypeLiteral<String>(){}).
      annotatedWith(new HelpTopicId("B")).toInstance("2");
}

public @interface HelpTopicId {
  public String helpTopicName();
}

public class Foo {
  public Foo(@HelpTopicId("A") String helpTopicId) {
    // I expect 1 and not 2 here because the actual parameter to @HelpTopicId is "A"
    assertEquals(1, helpTopicId);
  }
}

推荐答案

可能最简单的方法是使用@Provides方法:

Probably the simplest way to do this would be to use @Provides methods:

@Provides @HelpTopicId("A")
protected String provideA() {
  return "1";
}

或者,您可以创建HelpTopicId批注/接口的可实例化实现,类似于Names.named的实现(请参见

Alternatively, you could create an instantiable implementation of the HelpTopicId annotation/interface similar to the implementation of Names.named (see NamedImpl). Be aware that there are some special rules for how things like hashCode() are implemented for an annotation... NamedImpl follows those rules.

此外,使用new TypeLiteral<String>(){}是浪费的... String.class可以代替它使用.此外,对于Stringint等,通常应使用bindConstant()而不是bind(String.class).它更简单,要求您提供绑定注释,并且仅限于原语,StringClass文字和enum s.

Also, using new TypeLiteral<String>(){} is wasteful... String.class could be used in its place. Furthermore, for String, int, etc. you should typically use bindConstant() instead of bind(String.class). It's simpler, requires that you provide a binding annotation, and is limited to primitives, Strings, Class literals and enums.

这篇关于如何将特定参数绑定到自定义注释的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆