[英]Best practice for passing a type as a parameter in Java
I have a class that's supposed to recieve in the c'tor an implementation type (concrete class type) of some IStratagy interface, and create some objects of these recieved types. 我有一个类,应该在类中接收一些IStratagy接口的实现类型(具体类类型),并创建这些已接收类型的对象。 Something like that:
像这样:
Class SomeClass {
public SomeClass(Class<IStrategy> strategyClass) {
strategyClass.newInstance();
// catch nasty reflection exceptions...
}
}
I want to make sure that the parameter implements IStrategy. 我想确保该参数实现IStrategy。 I could recieve a parameter "IStrategy concreteStrategy" and then concreteStrategy.getClass().newInstance() but then it's still reflection which i'm trying to avoid.. What is the best practice for this problem in Java?
我可以先收到一个参数“ IStrategy concreteStrategy”,然后再收到concreteStrategy.getClass()。newInstance(),但仍在反思,我想避免这种情况。Java中此问题的最佳实践是什么?
I think you should use the following approach: 我认为您应该使用以下方法:
if( IStrategy.class.isAssignableFrom(strategyClass) ) {
.....
}
Basically this is like instanceof, but without creating the actual instance of your concrete strategy implementation. 基本上,这类似于instanceof,但是没有创建具体策略实施的实际实例。
Hope this helps 希望这可以帮助
Why not more simple like that: 为什么不这样简单:
Class SomeClass {
public SomeClass( IStrategy strategyClass ) {
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.