I assume that you really wanted to write the following, instead of using Object
on the left side. Since otherwise, it's really just about checking whether the object in the list is of the right type.
ClassName o = (classname)list.get(i);
Well, Java is statically typed. It's not possible that you give it a string and it gives you the corresponding static type, so that you can go without casting. Even with generics and Class<T>.cast
, the cast destination type is not given by a string, but by the generic type-argument T
, which is known at compile-time. You have to manually cast to the right type, or keep using the most common type (may be Object in your case).
If you do Class.forName(className)
, it gives you back an object of the type Class
which contains information about the type at runtime, so that it allows you to do
Class.forName("my.stuff.MyClass").newInstance()
But the cast wants a type - not an object of some type. That is why the compiler told you there is something wrong with that code.
The static type of the reference returned by that is of Object
. This is important: The dynamic type of an object that is referenced, and the static type of the reference that points to that object. The dynamic type of the object is what can be "controlled" by a string (by using Class.forName
), but the static type of the reference that you have to do with at compile time, and that is (just to give an example) used to select functions that overload each other, can not be determined by a string.