如何使用 Xtend 简洁地定义参数化类的 Guice 绑定?
以下 Java 代码设置 Guice 绑定。它使用 AbstractModule
的匿名子类提供 configure
的实现来设置绑定,并使用 TypeLiteral
的匿名子类创建 TypeLiteral
的绑定code>Map 到 HashMap
以获取特定类型参数(如此处所述)。
injector = Guice.createInjector(new AbstractModule() {
@Override protected void configure() {
bind(new TypeLiteral<Map<String, Event>>() {})
.to(new TypeLiteral<HashMap<String, Event>>() {});
}
});
我如何在 Xtend 中编写这个?
据我所知,Xtend 不支持实现匿名类或嵌套类(文档中没有提到它们,我也无法实现)猜测一个有效的语法)。因此,我必须在单独的 Xtend 文件中定义我的 AbstractModule
和每个 TypeLiteral
实现...不是很简洁。我是否缺少 Xtend 或 Guice 技巧来使这项工作顺利进行?
The following Java code sets up a Guice binding. It uses an anonymous subclass of AbstractModule
that provides an implementation of configure
to set the bindings, and anonymous subclasses of TypeLiteral
to create a binding of Map
to HashMap
for specific type parameters (as described here).
injector = Guice.createInjector(new AbstractModule() {
@Override protected void configure() {
bind(new TypeLiteral<Map<String, Event>>() {})
.to(new TypeLiteral<HashMap<String, Event>>() {});
}
});
How could I write this in Xtend?
As far as I can see, Xtend doesn't support implementing anonymous classes or nested classes (they aren't mentioned in the doc and I haven't been able to guess a working syntax). So I would have to define my AbstractModule
and each of my TypeLiteral
implementations in separate Xtend files... not very terse. Am I missing an Xtend or a Guice trick to make this work well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用闭包来实现模块接口:
injector = Guice.createInjector [
绑定(typeof(SomeType)).to(typeof(AnImplementation))
]
但是,这并不能解决类型文字的问题。你必须使用 Java,但我认为这不会有什么坏处。
You could use a closure to implement the module interface:
injector = Guice.createInjector [
bind(typeof(SomeType)).to(typeof(AnImplementation))
]
However, this will not solve the problem for the type literals. You'd have to use Java for that one, but I think it will not hurt.
引入一个真正的类而不是匿名的内部类怎么样?
what about intoducing a real class instead of a anonymous inner one?
与此相关的是,您可以使用 Xtend 闭包来实现 Guice 的 Provider 接口。
例如,在 Java 中调用 IResourceScopeCache.get:
在 Xtend 中变为
: >Provider.get()。
On a related note, you can use an Xtend closure to implement Guice's Provider interface.
For example, calling IResourceScopeCache.get in Java:
in Xtend becomes:
The trick is that
[|...]
is a function with zero parameters, in this caseProvider.get()
.