简体   繁体   English

从对象到对象的转换[]

[英]Casting from Object to Object[]

I was going though a part of my code, in which I had to explicitly type-case different data types into object type and vice versa, when I couldn't make sense of how something like this is done : 我要遍历代码的一部分,其中当我无法理解如何完成此操作时,必须将不同的数据类型显式地类型化为object类型,反之亦然:

(Object[])obj; //Casting an Object variable into and Object[]

I have tried to do the same with every other built-in and primitives. 我尝试对所有其他内置和基元执行相同的操作。 It does not work. 这是行不通的。

(String[])str; //Gives the error cannot cast from string to string[]

(int[])i; //Gives the error cannot cast from int to int[]

(char[])ch; //Gives the error cannot cast from char to char[]

(long[])l; //Gives the error cannot cast from long to long[]

(Integer[])in; //Gives the error cannot cast from int to Integer[]

where str is a of type string , i and in are of type int , ch is of type char , l is of type long . 其中str是string类型的a,i和in是int类型的,ch是char类型的,l是long类型的。

Then how is it allowed, and internally how is it accomplished when we do (Object[])obj; 然后如何允许它,以及在内部完成(Object[])obj;时如何完成它(Object[])obj; ?

Here obj is of type Object 这里objObject类型

Any instance of a refence type is also an Object. 引用类型的任何实例也是对象。

Arrays for example. 例如数组。

An array of String... is an Object. 字符串数组...是一个对象。

An array of Object... is an Object. 对象数组是一个对象。

Therefore, when the actual object is such an array, you can cast back. 因此,当实际对象是这样的数组时,可以回退。

But: an array of string is never a string. 但是:字符串数组绝不是字符串。 Therefore that cast does not work! 因此,该转换不起作用!

In code: 在代码中:

String[] strings = { "a", "b", "c" };
Object obj = strings;

That second line works because anything that is "an object", can assigned to an Object variable. 第二行有效,因为可以将“对象”中的任何内容分配给Object变量。 And because obj is actually referencing a string array, you can then cast back: 并且由于obj 实际上引用字符串数组,因此您可以回退:

String[] anotherVariablePointingToTheSameArray = (String[]) obj;

Keep in mind: that cast has only one meaning: you know better than the compiler. 请记住:强制类型转换只有一个含义: 比编译器了解得更多。 You know that "something" is actually (at runtime) more specific. 您知道“某事”实际上(在运行时)更具体。

In other words: you can only do a (X) y cast if y instanceOf(X) would return true! 换句话说:如果y instanceOf(X)返回true,则只能执行(X) y强制转换!

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

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