A better approach would be to generify the static method:
static <T extends Base> T create(Class<T> type){
// create concrete instance of type T and return it
}
so now the create
method is parameterized by the actual concrete type Class
object. You can use type
to create the appropriate sub-type, either via reflection or using nested if
statements.
Using generics has the advantage of giving you strong type safety for free, so you can avoid unchecked casts and go home after work with no worries.
EDIT: as an example if you had a no-arg constructor in each sub-class you could implement the above as:
return type.newInstance();
EDIT 2: To sum up the discussion, if the factory can't take the type or the logic to create the object depends in a non trivial way on the value of the argument, the only option is the following:
static Base create(String someParameter){
// create the concrete class and return it
}
And the client code will look like:
Base b = create("myArgument");
if(b instanceof SomeDerived){
SomeDerived d = (SomeDerived) b;
// use d
} else if(b instanceof OtherDerived){
// you get the idea
}
Not ideal but there's no way to generify the create
method without an instance of Class<? extends Base>
.