Add some defensive checks before casting.

Change-Id: I7614a663a068ab6be9bc1b6fcc897731a2218824