爪哇 - 强制转换一个对象到字符串类命名对象 [英] Java - Typecast a object to a String Class Named Object

查看:230
本文介绍了爪哇 - 强制转换一个对象到字符串类命名对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的对象。我想将其强制转换到另一个类。
所以,我们通常做的是 -

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";

有什么办法来强制转换在高压对象到一个名为类的 ToCastStringName

推荐答案

我不知道你的使用情况是什么,但可以实际使用的:

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

Class.forName(className).cast(someObject)

动态对象转换只知道类名。在你的情况下,code:

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);

将返回类型的对象汽车

有是关于在这个岗位使用和两种方法的权衡长时间的讨论:的Java类.cast()与转换操作符

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

这篇关于爪哇 - 强制转换一个对象到字符串类命名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆