如何检查param类的类型?

1 java android instanceof

我有以下方法:

public static String getServiceUri(Class<?> c) {

 // I'd like to check which type the parameter is...
 if(c.getClass().equals(MyClass.class)){
     do stuff 1
 } else {
     do stuff 2
 }
}
Run Code Online (Sandbox Code Playgroud)

调用方法: getServiceUri(MyClass.class);

getServiceUri我想基于ServiceClass的类型调用WebService.

我知道equals会比较对象实例,但在这种情况下我试图发现对象的类型.

任何人都知道如何使用这种方法进行比较?

nge*_*esh 7

instanceof operator is the best choice..
Run Code Online (Sandbox Code Playgroud)

你可以做这样的事情

if(c instanceof MyClass){
 //do your stuff

}
Run Code Online (Sandbox Code Playgroud)

  • 像问题一样,instaceof比匹配类要好得多.instanceof将继承考虑在内. (2认同)