簡體   English   中英

類型轉換為Java中類的字符串表示形式

[英]Type casting to String representation of a class in Java

我想將一個對象轉換為以字符串形式出現的幾種不同類型之一。 我知道強制轉換會解決,但我還沒有設法解決這個問題:

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

如何轉換此字符串,以便進行此類型轉換? 我試過Class.forName()卻沒有好結果:

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

...但是我收到有關Type mismatch: cannot convert from Class<capture-#1-of ?> to Loader投訴Type mismatch: cannot convert from Class<capture-#1-of ?> to Loader

另外,作為此問題的擴展,我需要首先將對象轉換為類型,還是可以將其用作方法調用內的即時轉換,如下所示:

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

我想這對您有用。

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