1

我有以下方法:

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
 }
}

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

getServiceUri想根据 ServiceClass 的类型调用 WebService。

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

有人知道我如何使用这种方法进行比较吗?

4

2 回答 2

7
instanceof operator is the best choice..

你可以做这样的事情

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

}
于 2012-04-04T06:50:13.197 回答
0
public static String getServiceUri(Class<?> classParam) {

    if(classParam instanceof MyClass){

     } 
}

This is WRONG. It does not even compile because classParam needs to be an actual instance(object) to use the instanceof operator: hence the name.

If you want to know if the classParam is exactly equal to MyClass.class:

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

    if(classParam == MyClass.class){
    }
}

However, if you want to check the entire hierarchy of classParam against MyClass then you can do classParam.isAssignableFrom(MyClass.class)

于 2015-01-16T21:51:30.003 回答