Java – when should a method accept a class type as a parameter?

I've seen the design of APIs that sometimes accept class types passed as parameters

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, if the class type can be obtained from the object, there is no need to pass the class at all, 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 the parameter of somemethod () and use [C] given below

public void someMethod(Object obj,int num ) {

 if(obj instanceof AClass) {
  //do something 
 }

}

So when should we choose the design shown in [a] instead of [b]? Are there any general principles to consider the design shown in [a]

PS: some APIs are designed as follows

Quartz example

Solution

Some obvious answers are:

>At any time, the method does not actually take an object as a parameter (for example, when you request an instance of a type from a di framework or factory, such as in the quartz example you provide). > The parameter passed in each time may be null, so you cannot call GetType on it, and instanceof will not indicate that the object is an instance of any type

Therefore, when the problematic method needs to generate an instance of the problematic class or provide some metadata about the class, it is meaningful to adopt class parameters, and these metadata do not need to create an instance

The only other consideration I want to point out is that generics can be used when accepting class parameters, such as the following method signature in Guice's injector interface:

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

Notice how this allows a method to declare that it returns an object of the same type you passed in as a class parameter, so you don't need to cast the object later You can also use generic wildcards (class ) to limit the types of classes that can be passed to methods

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>