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. 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. 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?
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.
Hope this helps
Why not more simple like that:
Class SomeClass {
public SomeClass( IStrategy strategyClass ) {
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.