简体   繁体   English

Java演员:哪个更好 - 命令式还是程序化方式?

[英]Java cast: Which is better — the imperative or programmatic way?

I have seen that there are two ways to cast an object in Java: 我已经看到有两种方法可以在Java中强制转换对象:

List<Object> l = new ArrayList();
ArrayList<Object> first = (ArrayList<Object>) l;
ArrayList<Object> second = ArrayList.class.cast(l);

Which is better and why? 哪个更好?为什么?

The better method is the most readable. 更好的方法是最可读的。 If you already know what class to do the type cast, use (ClassToUpcast) object . 如果您已经知道要进行类型转换的类,请使用(ClassToUpcast) object If you don't know the class but you have the Class<ClassToUpcast> clazz object, then use clazz.cast(object) . 如果您不知道该类但是您具有Class<ClassToUpcast> clazz对象,则使用clazz.cast(object)

ArrayList<Object> second = ArrayList.class.cast(l); should give you a compiler warning as this reflective operation is not able to check the type parameter of the list. 应该给你一个编译器警告,因为这个反射操作不能检查列表的类型参数。

ArrayList<Object> first = (ArrayList<Object>) l; on the other hand is a non-reflective operation for which the compiler can prove that the type parameters of List and ArrayList are the same and therefore that this is a safe operation. 另一方面,是一种非反射操作,编译器可以证明List和ArrayList的类型参数是相同的,因此这是一个安全的操作。

So it should be clear which one is to prefer. 所以应该清楚哪一个更喜欢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM