本文介绍了这两种方式在Java中投射有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种投放方式在Java中有什么区别?

What is the difference between these two ways of casting in Java?


  1. (CastingClass) objectToCast;

CastingClass.class.cast(objectToCast);

Class#cast(Object)的来源如下:

public T cast(Object obj) {
if (obj != null && !isInstance(obj))
    throw new ClassCastException();
return (T) obj;
}

因此, cast 基本上是一个泛型包装的cast操作,但我还是不明白为什么你需要一个方法。

So, cast is basically a generic wrapper of the cast operation, but I still don't understand why you would need a method for it.

推荐答案

你只能使用第一种形式的静态链接类。

You can only use the first form for statically linked classes.

在很多情况下,这是不够的 - 例如,你可能已经获得类实例使用反射或它被传递以你的方法作为参数;因此第二种形式。

In many cases that's not enough - for example, you may have obtained class instance using reflection or it was passed to your method as parameter; hence the second form.

这篇关于这两种方式在Java中投射有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:02