简体   繁体   中英

Tricking the JVM into casting arrays

I'd like to know is there is a way to cast an array of SuperType into and array of SubType . Like so:

SubType[] subArray = (SubType[])someSuperTypeArray;

I know that at runtime this throws a ClassCastException . A way to convert an array would be to copy it into another array. In my case, copying it is not an option.

Can I trick the JVM into beliving that the cast is valid, and bypass class type checks? Creating a reference to the array of SuperType , through which it is seen as some SubType array. (Possibly facing the dangers of unexplainable errors)

if you define the array like

SuperType[] array = {element1, element2};
SubType[] array2 = (SubType[]) array;

it will not work, however you can do this:

SuperType[] array = new SubType[]{element1, element2};
SubType[] array2 = (SubType[]) array;

You just have to make sure that the field array always has to be an array of your SubType when you're casting it.

There are only two possible array instances that someSuperTypeArray can point to.

  1. SuperType someSuperTypeArray = new SuperType[10]; : You can add SuperType objects or SubType objects to this array
  2. SuperType someSuperTypeArray = new SubType[10]; : You can only add SubType objects to this array. (Technically, you can add SuperType objects to this array at compile time but this will result in an ArrayStoreException at runtime)

Let's assume for a second that in case 1, you do manage to trick the JVM into allowing you to cast the someSuperTypeArray reference to a SubType[] reference. What should be done if someSuperTypeArray has an element of type SuperType ? You can't really expect the cast to implicitly discard all SuperType elements.

In case 2, is there any point of using a SuperType[] reference to a SubType[] array instance if all you want to do is cast the reference to a SubType[] reference. Just use a SubType[] reference in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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