Elad L.
Elad L.

Reputation: 639

How to use a String in an instance of

I was wondering how to make a boolean method that can receive a value and ask if a field is of that instance for example:

private boolean isInctance(String typeOfInctance){
     if(field inctenceof typeOfInctance){
           return false;
     }
     return true;
}

Upvotes: 0

Views: 80

Answers (1)

Pshemo
Pshemo

Reputation: 124225

instanceof works only with Classes, not Strings. If you want to determine it by String you can use

Class.forName("full.package.name.of.TestedType").isInstance(objectYouWantToTest)

Or to avoid Class.forName("full.package.name.of.TestedType") pass Class literal like String.class or Runnable.class and invoke isInstance on it.


Another thing is that

if (condition){
    return true;
}
return false;

can be simplified to

return condition;

Upvotes: 2

Related Questions