I have seen API’s designed where they at times accept class types to be passed as parameter’s.
For eg[a]:
class AClass {
//details
}
class Someclass {
public void someMethod(class klass, int num ) {
// some code
}
}
class client {
public static void main(String[] args) {
Someclass obj = new Someclass();
obj.someMethod(AClass.class, 10); // some sample use cases of client
}
}
Now in java, passing of class is not at all required if its possible to get the class type from the object, as explained below[b]
class AClass {
//details
}
class Someclass {
public void someMethod(AClass obj, int num ) {
// some code
}
}
class client {
public static void main(String[] args) {
Someclass obj = new Someclass();
AClass aclassObj = new Aclass();
obj.someMethod(aclassObj, 10);
}
}
I can also change the parameter of someMethod() and use as given below [c]
public void someMethod(Object obj, int num ) {
if(obj instanceof AClass) {
//do something
}
}
So when should we choose the design as shown in [a] instead of [b] ? Are there any general principles to consider for design shown in [a].
PS: Some API’s designed like that are shown below
A couple of obvious answers are:
getTypeon it, andinstanceofwon’t indicate that the object is aninstanceofany type.So it makes sense to take a
classargument when the method in question either needs to produce an instance of the class in question or provide some metadata about that class which shouldn’t require an instance to be created.The only other consideration I’d point out is that it is possible to use generics when accepting a class parameter, as in the following method signature on Guice’s
Injectorinterface:Notice how this allows the method to declare that it’s returning an object of the same type that you pass in as a class parameter, so you don’t need to cast the object afterward. You can also use the generic wildcards (
Class<? extends Foo>) to restrict the types of classes that can be passed into the method.