Avoid invalid downcasts

Change-Id: I1666321916d08b326bb0c1c1f21273d568523691