Possible Duplicate:
Java Class.cast() vs. cast operator
I am unsuccessfully trying to find out what Class.cast() does or what it may be good for. At the same time I am wondering whether I can somehow cast an object via reflection.
First I thought something like the lines below might work:
Object o = "A string";
String str = Class.forName("java.lang.String").cast(object);
But without an explicit cast it does not work.
So what is the cast method of Class class good for? And is it somehow possible just with reflection to cast objects, so you find the object’s class, use Class.forName on it and cast it somehow?
An example where is does work:
which allows you to write:
The reason your code doesn’t work is that Class.forName() returns a
Class<?>, i.e. a class object representing an unknown type. While the compiler could possibly infer the type in your example, it can not in general. Consider:what’s the type of this expression? Clearly the compiler cannot know what the class name will be at runtime, so it doesn’t know whether
is safe. Therefore it requests an explicit cast.