什么时候应该使用类的java 5方法? [英] When should I use the java 5 method cast of Class?

查看:133
本文介绍了什么时候应该使用类的java 5方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看一些代码,我遇到了以下代码

Looking through some code I came across the following code

trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));

我想知道这种方式是否有任何优势

and I'd like to know if casting this way has any advantages over

trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto);

我问开发商负责人他说他用过它是因为它是新的(没有'对我来说似乎是一个特别好的理由),但是当我想要使用该方法时,我很感兴趣。

I've asked the developer responsible and he said he used it because it was new (which doesn't seem like a particularly good reason to me), but I'm intrigued when I would want to use the method.

推荐答案

这些陈述并不相同。 cast方法是一个普通的方法调用( invokevirtual JVM指令),而另一个是语言构造( checkcast 指令) 。如果你在上面显示,你应该使用第二种形式:(TrTuDocPackTypeDto)packDto

These statements are not identical. The cast method is a normal method invocation (invokevirtual JVM instruction) while the other is a language construct (checkcast instruction). In the case you show above, you should use the second form: (TrTuDocPackTypeDto) packDto

cast 方法用于带泛型的反射编程,当你有一个类变量类型的实例时。您可以像这样使用它:

The cast method is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this:

public <T> Set<T> find(Class<T> clz, Filter criteria) {
  List<?> raw = session.find(clz, criteria); /* A legacy, un-generic API. */
  Set<T> safe = new HashSet<T>();
  for (Object o : raw) 
    safe.add(clz.cast(o));
  return safe;
}

这为您提供了一种安全的方法来避免简单地转换原始数据的错误选择键入通用类型:

This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type:

/* DO NOT DO THIS! */
List raw = new ArrayList();
...
return (List<Widget>) raw;

编译器会警告你,从列表到列表< Widget>的未选中强制转换,这意味着在省略号中,有人可能会在原始列表中添加 Gadget ,最终会导致 ClassCastException 当调用者迭代返回的(假设的) Widget 实例列表时。

The compiler will warn you, Unchecked cast from List to List<Widget>, meaning that in the ellipsis, someone could have added a Gadget to the raw list, which will eventually cause a ClassCastException when the caller iterates over the returned list of (supposed) Widget instances.

这篇关于什么时候应该使用类的java 5方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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