1
obj instanceof Arrays

would help be know if obj is instance of Arrays, but what i want to know if what operator to use to find if obj is a subclass of Arrays ?

Assume class Animal is super class of Dog.

Dog d = new Dog().

if (dog "which operator ? " Animal) would result in true ?

jmj
  • 237,923
  • 42
  • 401
  • 438
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

3 Answers3

3

instanceof will return true for subclasses as well. An instance of Dog is also an instance of Animal.

CupawnTae
  • 14,192
  • 3
  • 29
  • 60
2

See isAssignableFrom()

Animal.class.isAssignableFrom(dog.getClass())

will return you true if Dog is child of Animal (either extends or implements)

this will help you if you have type determined at runtime, if it is fixed to check against type then you can use instanceof operator

also while using this method make sure to handle null

jmj
  • 237,923
  • 42
  • 401
  • 438
  • If you want to make sure that dog's class is exclusively a child class of `Animal` then you want to say `Animal.class.isAssignableFrom(dog.getClass()) && !dog.getClass().isAssignableFrom(Animal.class)` – CodeBlind Jul 08 '14 at 23:53
  • `isAssignableFrom()` is neither a keyword nor an operator. Also, what you've written is mostly equivalent to `dog instanceof Animal` - the exception being if `dog` is `null`, which, according to the question, it's not – CupawnTae Jul 08 '14 at 23:53
1

Jigar's solution is probably best, but you could probably do it this way too:

dog instanceof Animal && !dog.getClass().equals(Animal.class)

This will only return true if dog's class is a child of Animal but is not a base-level Animal instance.

CodeBlind
  • 4,519
  • 1
  • 24
  • 36