通过反射和使用 Class.cast() 进行投射
我没有成功地尝试找到了解 Class.cast()
的作用或它可能有什么用处。同时我想知道是否可以通过反射以某种方式投射对象。
首先,我认为类似下面的代码可能会起作用:
Object o = "A string";
String str = Class.forName("java.lang.String").cast(object);
但是如果没有显式的强制转换,它就不起作用。
那么Class
类的cast
方法有什么用呢?是否可以通过反射来强制转换对象,以便找到对象的类,在其上使用 Class.forName 并以某种方式强制转换它?
Possible Duplicate:
Java Class.cast() vs. cast operator
I am unsuccessfully trying to find out what Class.cast()
does or what it may be good for. At the same time I am wondering whether I can somehow cast an object via reflection.
First I thought something like the lines below might work:
Object o = "A string";
String str = Class.forName("java.lang.String").cast(object);
But without an explicit cast it does not work.
So what is the cast
method of Class
class good for? And is it somehow possible just with reflection to cast objects, so you find the object's class, use Class.forName
on it and cast it somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个例子,它可以工作:
它允许你写:
你的代码不起作用的原因是 Class.forName() 返回一个
Class
,即代表未知的类对象类型。虽然编译器可能会推断示例中的类型,但通常不能。考虑一下:这个表达式的类型是什么?显然编译器无法知道运行时的类名是什么,因此它不知道是否
安全。因此它要求显式强制转换。
An example where is does work:
which allows you to write:
The reason your code doesn't work is that Class.forName() returns a
Class<?>
, i.e. a class object representing an unknown type. While the compiler could possibly infer the type in your example, it can not in general. Consider:what's the type of this expression? Clearly the compiler cannot know what the class name will be at runtime, so it doesn't know whether
is safe. Therefore it requests an explicit cast.
Class.forName
的返回类型将为Class
。你想要Class<?扩展 String>
,例如使用String.class
。不是很有用,直到您开始用某种接口类型替换
String
。无论如何,反思通常是邪恶的。
The return type of
Class.forName
will beClass<? extends Object>
. You wantClass<? extends String>
, for instance usingString.class
.Not very useful, until you start replacing
String
with some kind of interface type.In any case, reflection is generally evil.
您可以使用以下代码来避免警告:
而以下代码将引发警告:
You can avoid a warning e.g. with the following code:
while the following code will raise a warning:
Class.forName
将返回一个Class
类型对象。cast
方法将返回 Class 的类型参数。因此,在这种情况下它将返回一个 ? (对象)类型对象。您应该尝试:
另请参阅 Class.cast()
Class.forName
will return aClass<?>
type object. Thecast
method will return the type parameter of Class. Thus, in this case it'll return a ? (Object) type object.You should try:
See also Class.cast()