Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check class of generic object variable [duplicate]

Tags:

java

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.

like image 489
zai-turner Avatar asked Jun 10 '26 05:06

zai-turner


1 Answers

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.

like image 149
Thomas Avatar answered Jun 11 '26 18:06

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!