简体   繁体   中英

Type casting to String representation of a class in Java

I want to cast an object to one of a few different types that comes to me in the form of a string. I know the casting will work out but I haven't managed to work out how to address this:

Tools a = new Loader(); //Loader extends the Tools abstract class
String cl = "Loader";
Loader b = (cl) a; //Obviously this doesn't work
Loader b = (Loader) a; //This is the effect I want, but from a String repr. of Loader

How can I convert this string so that this type casting works out? I have tried Class.forName() without good results:

Loader b = (Class.forName(cl)) a;

...but I get complaints about Type mismatch: cannot convert from Class<capture-#1-of ?> to Loader

Also, as an extension of this question, do I need to cast the object to a type first or will I be able to use it as an on-the-fly casting inside a method invocation or so, something like this:

doSomething(("Loader") b); //Assuming doSomething requires a Loader type...

I guess this will work for you.

String c1 = "Loader";
Class c = Class.forName(c1);
Loader b = (c)a;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM