Avoid invalid downcasts

Change-Id: I8550da2c6afb4e7de394879ef75312a0c9c2df25