Is there a valid class Type variable that can be used with the instanceof
operator? For Example:
String s = "abc";
Class<?> classType = String.class;
if (s instanceof classType) {
//do something
}
as an alternative to this:
if (s.getClass() == classType) {
//do something
}
Would there be any performance benefit?
What you're doing is not actually the same. Consider what happens with subclasses (I know you can't subclass
String
, so in theString
case it doesn't matter).If you have an object and you want to know if it is an instanceof a certain type and you have the
Class
object, you can use theClass#isInstance
method.In either case, I expect performance differences to be insignificant.
There's also
As for performance, I'd expect the differences between any of these to be negligible.