Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class.forName casts

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?

like image 347
Johm Don Avatar asked Jul 24 '11 16:07

Johm Don


3 Answers

Class.forName returns a Class 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.

like image 154
T.J. Crowder Avatar answered Oct 04 '22 06:10

T.J. Crowder


You can cast with the class object's .cast method:

Object a;
String b = "testing";
a = Class.forName("java.lang.Object").cast(b);

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 type T (from Class<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 of Class.forName is Class<?>, which means that its cast method can only return Object.

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

Object a;
String b = "testing";
a = b;

has the same effect here.

like image 38
Paŭlo Ebermann Avatar answered Oct 04 '22 05:10

Paŭlo Ebermann


If it is required to cast an instance this is a way to do it

String className         = "YourClass";
Class someClass          = Class.forName( className );
Constructor constructor  = (Constructor) someClass.getConstructor();
Object someInstance      = constructor.newInstance();

// now you can cast as allways.
(YourClass) (someInstance)
like image 21
Edgardo Genini Avatar answered Oct 04 '22 06:10

Edgardo Genini