Check if an object is an instance of any one of a list of classes (Android)

I've been looking at this for a while, and whilst it's not critical, I was wondering if there is a neat way (1 liner perhaps) that I can use to check if an object is an instance of any of several classes for example, I could do:

if(anObject instanceof Pupil){ ... } else if(anObject instanceof Teacher) { ... }

And so on and so forth. Is there a better way to do this, or is this as good as I'm going to get?

-------------Problems Reply------------

Make a Collection of Class objects of your choice and...

if(myClasses.contains(obj.getClass())) {
// obj is one of the classes I care about, so do something

Of course if you intend to cast obj afterwards, this won't help (but that would be, as I said in my comment, an indication of a design problem).

instanceof is what you would want. Keep in mind that instanceof will return true for superclasses as well.

If you want to see if an object is a direct instance of a class, you could compare the class. You can get the class object of an instance via the getClass() method. And you can statically access a specific class via ClassName.class.

An example:

if (anObject.getClass() == Pupil.class) {}

In the above example, the condition is true if anObject is an instance of Pupil, but not if anObject is an instance of a subclass of Pupil.

In comparison:

if (anObject instanceof Pupil) {}

In the instanceof example, the condition is true if anObject is an instance of Pupil, or if anObject is an instance of a subclass of Pupil.

Normally, instanceof is the correct approach.

As long as you only need to check the exact class of the object and not superclasses, then you could have a list of the classes you want to check for, and simply check if that list contains the class you have.

Here's some code...

//Set up list of classes
private static final List<Class> CLASSES = Arrays.asList(new Class[] { String.class, Double.class });

Then subsequently when you want to check, it's a one liner...

if(CLASSES.contains(anObject.getClass())) { ... }

Through the use of reflection, java/android has a method isAssignableFrom() which allow you to test if a particular Class object can be assigned from another. Using this fact, you could place your list of test classes into a Class[] and check each and every one through a for loop, as follows:

public static boolean assignableFrom(Class test, Class[] candidates){
for(Class candidate : candidates){
return true;

return false;

in this case, the class under test can be checked against multiple classes for both equivalence and inheritance, meaning that the method will return true even if one of the candidate classes is a superclass of the test class.

If you want instance level relationship only, consider constructing a HashSet of your candidate classes and check if your test object's class in contained within this HashSet (since this gives better performance than a iterative lookup).

you can try to cast your object to Person, and see if you are getting a ClassCastException

Category:java Views:4 Time:2019-01-02
Tags: java android

Related post

  • Python: how to check if an object is an instance of a namedtuple? 2010-01-30

    How do I check if an object is an instance of a Named tuple? --------------Solutions------------- Calling the function collections.namedtuple gives you a new type that's a subclass of tuple (and no other classes) with a member named _fields that's a

  • A clean way of checking whether an object is an instance of window.constructor 2011-06-03

    The title pretty much says it all. I need to check whether an object is an instance of the DOM:Window interface. window will pass the test, window.frames[xyz] as well, should the iframe exist. The most intuitive way appears to be a simple instanceof

  • How do you get a javascript function to only be running one instance at any one point? 2009-08-22

    I have some code that I'd like to run on a page. My problem is that I don't want it to be run more than once at any one point. It can run multiple times, but just not while another instance of itself is running. I'm using jQuery and loading ajax cont

  • How to check if an object is an instance of a NodeList in IE? 2008-09-30

    Why is NodeList undefined in IE6/7? <form action="/" method="post" id="testform"> <input type="checkbox" name="foobar[]" value="1" id="" /> <input type="checkbox" name="foobar[]" value="2" id="" /> <input type="checkbox" name="fo

  • how to check if an object exists in an array which is found in a global class in C# 2011-08-05

    I am making a game which has a global (static) class called MedGameController. In my class I have two arrays of fifteen objects each which hold the logic for each players units. In the game the player's go to a form where they see their already creat

  • Can I check if an object is kind of a specific class, in PHP? 2009-12-27

    This question already has an answer here: How to Check for a Specific Type of Object in PHP 4 answers Example: A method is supposed to return an instance of a SpecificClass. How can I check that return value if it is from that class? --------------So

  • Checking if the object is of same type 2010-11-26

    Hello I need to know how to check if the object of the same type in C#. Scenario: class Base_Data{} class Person : Base_Data {} class Phone : Base_data {} class AnotherClass{ public void CheckObject(Base_Data data){ if(data.Equals(Person.GetType())){

  • Check that an object is instanceof angular 2014-07-28

    HTML: <div id="obj"></div> in jQuery: var obj = $('#obj'); obj instanceof jQuery; 'true' So, I assumed that angular.module('app', []) instanceof angular.module() to be true.. Instead I get: Error: [$injector:nomod] http://errors.angularjs

  • How to check if an object is nullable? 2008-12-17

    How do I check if a given object is nullable in other words how to implement the following method... bool IsNullableValueType(object o) { ... } EDIT: I am looking for nullable value types. I didn't have ref types in mind. //Note: This is just a sampl

  • Factory pattern in C#: How to ensure an object instance can only be created by a factory class? 2009-02-05

    Recently I've been thinking about securing some of my code. I'm curious how one could make sure an object can never be created directly, but only via some method of a factory class. Let us say I have some "business object" class and I want to make su

  • Where to check if an object is null or not? 2009-04-01

    Where do you check if an object that you are passing to a method is null or not? Should an object need to be tested before calling a method? or within the method that is using the argument? public class Program { public static void Main(string[] args

  • To check if an object is empty or not 2009-10-26

    I want to check in my function if a passed argument of type object is empty or not. Sometimes it is empty but still not null thus I can not rely on null condition. Is there some property like 'length'/'size' for flex objects which I can use here. Ple

  • Python: check if an object is a list or tuple (but not string) 2009-12-02

    This is what I normally do in order to ascertain that the input is a list/tuple - but not a str. Because many times I stumbled upon bugs where a function passes a str object by mistake, and the target function does for x in lst assuming that lst is a

  • How can I check whether an object reference is still valid? 2010-01-28

    I have an issues where I am trying to determine if a reference to an object is valid. But it seems to be returning strange results. procedure TForm1.Button1Click(Sender: TObject); var form1 : TForm; ref2 : TControl; begin form1 := TForm.Create(nil);

  • How to check if an object is not an array? 2010-02-15

    So i have a function that needs to check if an argument is an object, but this fails because: typeof [] // returns 'object' This is a classic javascript gotcha, but i cant remember what to do to actually accept objects, but not arrays. --------------

  • How to check if an object is defined? 2010-03-29

    I would like to check if an object is defined or exists using C#. Something like this: if (defined(Object)){ } --------------Solutions------------- You check if it's null in C# like this: if(MyObject != null) { //do something } If you want to check a

  • Check if Ruby object is a Boolean 2010-06-12

    Can't seem to find how to check if an object is a boolean easily. Is there something like this in Ruby? true.is_a?(Boolean) false.is_a?(Boolean) Right now I'm doing this and would like to shorten it: some_var = rand(1) == 1 ? true : false (some_var.i

  • Save custom object array in instance state 2010-07-11

    I have a List<CustomObject> (where CustomObject comes from an external library -- I can't make changes to it). I want to save this in onSaveInstanceState(Bundle), but I can't seem to do it. Here are the options that I've tried: outState.putSeri

  • Ruby on Rails: how do I check if a variable in an instance of a class? 2010-08-06

    In Java, you can do instanceof. Is there a Ruby equivalent? --------------Solutions------------- It's almost exactly the same. You can use Object's instance_of? method: "a".instance_of? String # => true "a".instance_of? Object # => false Ruby a

  • Replacing a db4o stored object with an instance of a subclass 2010-08-20

    I want to change all objects that match a condition to use a specific/new subclass. There are no other subclasses being used with the stored objects, so its in all cases a change from the base class to its subclass. In order to keep all references po

  • how can I check if an object exists in C++ 2010-09-04

    I am trying to write a function that will check if an object exists: bool UnloadingBay::isEmpty() { bool isEmpty = true; if(this->unloadingShip != NULL) { isEmpty = false; } return isEmpty; } I am pretty new to C++ and not sure if my Java backgrou

  • Check if a object is the same 2010-10-08

    Im doing some queries to a active directory, building up my own Dictionary to contain name, phone and email per user. then i store user to a file, something like this: domain\groupt\group\user;<checksum> where path before ; is the unique id for

  • Python: Checking if an object is atomically pickleable 2010-11-16

    What's an accurate way of checking whether an object can be atomically pickled? When I say "atomically pickled", I mean without considering other objects it may refer to. For example, this list: l = [threading.Lock()] is not a a pickleable object, be

  • Check if an object belongs to a class in Java 2010-11-28

    This question already has an answer here: How to determine an object's class (in Java)? 7 answers Is there an easy way to verify that an object belongs to a given class? For example, I could do if(a.getClass() = (new MyClass()).getClass()) { //do som

Copyright (C), All Rights Reserved.

processed in 0.074 (s). 11 q(s)