如何用 guice 代替反射?
我长期以来一直使用反射来将模块与“处理程序”解耦。
我有一个这样构建的代码库:
static enum AnimalHandlers {
Dog(Dog.class),
Cat(Cat.class);
private final Class c;
AnimalHandlers(Class class)
{
this.c=class;
}
public Class getAnimalHandler()
{
return c;
}
}
然后在我的代码中,我有一个方法,该方法将“Animal”枚举作为输入并使用反射(也就是说,它从枚举中获取类并调用“newInstance”)调用必要的处理程序。
我认为使用 Guice 解决方案会更清晰。我怎样才能摆脱枚举/反射并简单地使用 guice 用域特定的逻辑处理程序“水合”我的控制模块?
I have long used reflection to decouple modules from "handlers".
I have a code base which is architected like this :
static enum AnimalHandlers {
Dog(Dog.class),
Cat(Cat.class);
private final Class c;
AnimalHandlers(Class class)
{
this.c=class;
}
public Class getAnimalHandler()
{
return c;
}
}
Then later in my code, I have a method which takes an "Animal" enum as input and uses reflection (that is, it gets the class from the enum and invokes "newInstance") to invoke the necessary handler.
I think the solution would be cleaner with Guice. How can I get rid of the enum/reflection and simply use guice to "hydrate" my control module with domain specific logic handlers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以很好地使用
MapBinder
,并为每个可能的AnimalEnum
值定义一个绑定。You could well use a
MapBinder<AnimalEnum, AnimalHandler>
, and define a binding for each possibleAnimalEnum
value.我想这里一定有更好的模式。我对 Animal 枚举如何与处理程序交互有点困惑,但我会提出一些一般性建议,也许其中一个会坚持下去。
Animal.setHandler(...)
注册自己吗?然后您可以调用Animal.Dog.getHandler()
来获取 Dog 的处理程序。AnimalHandlerMapper
也会更好。我假设有一个通用接口是可能的,即使它只是一个标记接口。代码:
希望这有帮助。
I think that there must be a better pattern here. I'm a little confused as to just how the
Animal
enum interfaces with the handler but I'll make some general suggestions and maybe one will stick.Animal
enum and you want to decouple the classes. Fine.Animal.setHandler(...)
? Then you could just callAnimal.Dog.getHandler()
to get Dog's handler.AnimalHandlerMapper
would also be better. I assume there a common interface is possible, even if it just a marker interface.Code:
handlerMap.get(animal).create(animal)
or some such. This would be much cleaner than using reflection.AnimalHandlerMapper
to completely decouple it.Hope this helps.