3

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.

zai-turner
  • 75
  • 1
  • 10
  • 1
    I might be wrong but I think you can't have variable as the right argument of the `instanceof` operator, it has to be a concrete class/interface – Amongalen Dec 11 '19 at 15:25
  • 4
    Well, "abc" is not instance of a `Class`, even if Class *describes* String class. You may want to use `testClass.isInstance(variable)`. But to be honest usually this represents [XY problem](https://meta.stackexchange.com/q/66377), can you explain *why* do you want to create such code? – Pshemo Dec 11 '19 at 15:27
  • 1
    Please stick to Java naming conventions. The method should be called `debug` (camelCase, not PascalCase). – Zabuzard Dec 11 '19 at 15:27
  • 1
    And not sure about the many upvotes here ... it is really not like the OP did a lot of prior research it seems ... – GhostCat Dec 11 '19 at 15:34
  • @GhostCatsaysReinstateMonica Correct! – Seelenvirtuose Dec 11 '19 at 15:35
  • Agreed. But imo the question is pretty clear and well posted. Enough to be worth no down-vote at least. – Zabuzard Dec 11 '19 at 19:17

1 Answers1

5

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.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • ... at which point the method is more or less obsolete since it is just an alias to a more clear method call `testClass.isInstance(variable)` vs `Debug(variable, testClass)`. – Zabuzard Dec 11 '19 at 15:28
  • Although correct, I question the value of such a method. Instead of calling `Debug(someVariable, String.class)`, why not simply call `String.class.isInstance(someVariable)` beforehand? – Seelenvirtuose Dec 11 '19 at 15:29
  • 1
    @Zabuza Of course, but that is left as an exercise to the reader ;) – Thomas Dec 11 '19 at 15:29