In Java, will using Class.forName in a cast result in the object being cast to a class or being cast to the cast found. As an example, if you did this
Object a;
String b = "testing";
a = (Class.forName("java.lang.Object")) b;
Would a be an instance of Class or an instance of Object?
If it is required to cast an instance this is a way to do it
Class.forName
returns aClass
instance. I'm fairly certain your code as quoted doesn't compile, you're trying to use a function call as a cast.Update: Just had a thought: If you're asking how to use a dynamically-loaded class in a cast, you basically can't. Casting is (mostly) a compile-time thing. Have the dynamically-loaded class implement an interface you can compile into your code and then cast to that, or if you can't do that, use reflection to access the dynamically-loaded class' members.
Class.forName always returns the Class.
You can cast with the class object's
.cast
method:But you seem to have wrong ideas about casting - in Java, casting does not change any object, it just tells the compiler that the object is of some type, and on runtime, the VM will test if this is really the case (if the compiler can't already prove it). If you "cheated", the VM will throw an
ClassCastException
here (it will not convert your object).(It works a bit different if primitive types are involved.)
The Class object's
cast
method is a generic variant of this same mechanism. Since it has the return typeT
(fromClass<T>
), this allows generic code to cast an unknown object to some class type, where this class object corresponds to a type variable. This will not help you here - the return type ofClass.forName
isClass<?>
, which means that its cast method can only returnObject
.And anyway, casting to java.lang.Object has no effect (it will always succeed), other than hiding the to the compiler that the value has some specialized type. (This might matter if you have overloaded methods.)
Simply writing
has the same effect here.