简体   繁体   English

类型转换为Java中类的字符串表示形式

[英]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: 我试过Class.forName()却没有好结果:

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

...but I get complaints about Type mismatch: cannot convert from Class<capture-#1-of ?> to Loader ...但是我收到有关Type mismatch: cannot convert from Class<capture-#1-of ?> to Loader投诉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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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