我为什么要使用java.lang.Class.cast [英] Why would I use java.lang.Class.cast

查看:104
本文介绍了我为什么要使用java.lang.Class.cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

什么时候应该使用Class 5的java 5方法转换?

我最近偶然发现了这样一段代码:

  Object o = ..; 
Foo foo = Foo.class.cast(o);

实际上我甚至都没有意识到java.lang.Class有一个cast方法,所以我研究这些文档以及我所收集的内容只是对Class对象所代表的类进行转换。因此,上面的代码大致相当于

  Object o = ..; 
Foo foo =(Foo)o;

所以我想知道为什么我想用cast方法而不是简单地做一个老方法。有没有人有一个很好的例子,其中cast方法的用法比简单的转换更有用?

Java Class.cast()与转换运算符


我只使用Class.cast(Object)来避免在泛型土地中发出警告。我经常看到方法做这样的事情:



  @SuppressWarnings(unchecked)
< T> T doSomething(){
Object o;
// snip
return(T)o;
}




通常最好用 p>



 < T> T doSomething(Class< T> cls){
Object o;
// snip
return cls.cast(o);
}




这是Class.cast的唯一用例对象)我曾经遇到过。



Possible Duplicate:
When should I use the java 5 method cast of Class?

I recently stumbled upon a piece of code that went like this:

Object o = .. ;
Foo foo = Foo.class.cast(o);

I was actually not even aware that java.lang.Class had a cast method, so I looked into the docs, and from what I gather this does simply do a cast to the class that the Class object represents. So the code above would be roughly equivalent to

Object o = ..;
Foo foo = (Foo)o;

So I wondered, why I would want to use the cast method instead of simply doing a cast "the old way". Has anyone a good example where the usage of the cast method is beneficial over doing the simple cast?

解决方案

From Java Class.cast() vs. cast operator

I've only ever used Class.cast(Object) to avoid warnings in "generics land". I often see methods doing things like this:

@SuppressWarnings("unchecked")
<T> T doSomething() {
Object o;
// snip
return (T) o;
}  

It's often best to replace it by

<T> T doSomething(Class<T> cls) {
Object o;
// snip
return cls.cast(o);
}  

That's the only usecase for Class.cast(Object) I've ever come across.

这篇关于我为什么要使用java.lang.Class.cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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