When should a method accept a class type as a parameter?

I saw an API where they sometimes accept class types that should be passed as parameters. For example: [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 class transfer is not required at all if it is possible to get the class type from an object, as described 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 someMethod () parameter and use as below [c]

 public void someMethod(Object obj, int num ) { if(obj instanceof AClass) { //do something } } 

So, when should we choose a design as shown in [a] instead of [b]? Are there any general design principles shown in [a].

PS: Some APIs created in this way are shown below.

Quartz example

+4
source share
3 answers

A few obvious answers:

  • At any time when the method does not actually accept the object as a parameter (for example, when you request an instance of a type from the DI or factory framework, for example, in the quartz example you presented).
  • Each time the parameter you pass can be NULL, so you cannot call getType on it, and instanceof will not indicate that the object is instanceof any type.

Thus, it makes sense to take the class argument when the method in question must either create an instance of the class in question or provide some metadata about this class that does not require instantiation.

The only other consideration that I would like to point out is that when accepting a class parameter, you can use generics, as in the following method signature on the Guice Injector interface:

 <T> T getInstance(Class<T> type); 

Note how this allows the method to declare that it returns an object of the same type that you pass as a parameter to the class, so you do not need to drop the object later. You can also use common wildcards ( Class<? extends Foo> ) to limit the types of classes that can be passed to a method.

+1
source

Pass a class description (class object) if you need to process it. Pass an object (which is an instance of the class) if you need an object to process.

0
source

Another example may be here - where the type of the returned object (in this case, the objects in the list) depends on the type of class.

Many instances where this is required can now be replaced when developing an API that uses generics, but for some problems it still offers a concise and clear syntax.

0
source

Source: https://habr.com/ru/post/1369379/


All Articles