How to check type of param class?

Go To StackoverFlow.com

1

I have the following method:

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

Invoke method: getServiceUri(MyClass.class);

On getServiceUri I want to call a WebService based on the type of a ServiceClass.

I know that equals will compare objects instance, but in this case I'm trying to discover the type of object.

Anyone know how I can compare using this kind of approach?

2012-04-04 06:47
by Adriano


7

instanceof operator is the best choice..

you can do something like this

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

}
2012-04-04 06:50
by ngesh
instaceof is much better than matching classes as the questionner does. instanceof takes inheritance into account - Snicolas 2012-04-04 06:56
@Snicolas.. very true. - ngesh 2012-04-04 06:58
I wish SO allowed you to make one letter fixes like the capital O in instanceOf above - rob5408 2014-05-21 13:15
@rob5408 .. done. - ngesh 2014-05-21 13:16
@ngesh, thanks - rob5408 2014-05-21 13:48


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-16 21:51
by Nikolaii99
Ads