I am writing a function that tests whether variable of type Object is of a given type. For example, if I put in "This is a string" and String.class as the params, it should return true.
I have tried the following code:
public static boolean Debug(Object variable, Class<?> testClass) {
if (variable instanceof testClass) {
return true;
}
return false
}
However, I got the error: "testClass cannot be resolved to a type".
I am not quite sure why this is.
Any suggestions would be greatly appreciated.
The error message is correct: testClass is not a type, it's an object, of type Class<String>. The instanceof operator can only be used with types that are given at compile time. Instead, you can do your check with the Class#isInstance method of your Class object:
public static boolean Debug(Object variable, Class<?> testClass) {
if (testClass.isInstance(variable)) {
return true;
}
return false;
}
A better way to write that would be:
public static boolean Debug(Object variable, Class<?> testClass) {
return testClass.isInstance(variable);
}
At this point, it's so small that I would start to wonder whether this method is worth having at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With