0

I have a object of a class. I want to typecast it to another class. So, what we generally do is -

HeavyVehicle hv = new HeavyVehicle();
Truck tr = (Truck) hv;

if we typecast the hv object to truck classes object.

But if the name of the class is stored in a string like this-

String ToCastStringName = "Truck";

Is there any way to typecast the hv object to a class named ToCastStringName?

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
  • Please do not post the same question multiple times. Instead, use the edit button to update your question. – Matt Jun 19 '15 at 06:49

3 Answers3

1

I'm not sure what your use case is but you can actually use:

Class.forName(className).cast(someObject)

to dynamically cast an object knowing only the class name. In your case, the code:

HeavyVehicle hv = new HeavyVehicle();
String ToCastStringName = "Truck";
Class.forName(ToCastStringName).cast(hv);

would return an object of the type Truck.

There's a long discussion about uses and tradeoffs of either approach in this post: Java Class.cast() vs. cast operator

Community
  • 1
  • 1
Mike Laren
  • 8,028
  • 17
  • 51
  • 70
0

You can use Class.forName(ToCastStringName).cast(hv) provided ToCastStringName is a fully qualified name of class.

barunsthakur
  • 1,196
  • 1
  • 7
  • 18
0

I believe using Class.forName() is a lot more complicated in android (than indicated by the Java solutions). I've tried to follow several "java" examples, and have yet to get anything that didn't result in a ClassNotFound error in Andriod Studio.

Android is its own separate language, and some things just working differently here. I searched, and it appears the answer is a lot more complicated in Android. It apparently has to do with how their packed into APKs. As you can see from this post, the solution is quite involved.

http://yenliangl.blogspot.com/2009/11/dynamic-loading-of-classes-in-your.html
NameSpace
  • 10,009
  • 3
  • 39
  • 40