Question

I wanted to cast a series of objects in an array to different types based upon user preferences.

Is it possible to reference primitive-types from an array for casting?

public void MakeByteBuffer(float x, float y, float z) {
    xyz[0] = x;
    xyz[1] = y;
    xyz[2] = z;
    byteBufferSend.rewind();
    for (int i = 0; i < whatToSendVarArray.length; i++) {
        switch (whatToSendTypeArray[whatToSendVarArray[i]]) {
        case 0:// byte
            byteBufferSend.put((byte) xyz[whatToSendVarArray[i]]);
            break;
        case 1:// short
            byteBufferSend
                    .putShort((short) xyz[whatToSendVarArray[i]]);
            break;
        case 2:// int
            byteBufferSend
                    .putInt((int) xyz[whatToSendVarArray[i]]);
            break;
        // Plus more types...
        }
        byteArrayDataToSend = byteBufferSend.array();
    }
}

Ideally I would like:

typeArray={byte,short,int,long,float,double};
byteBufferSend.put???((typeArray[i]) xyz[whatToSendVarArray[i]]);

What is the best practice?

Was it helpful?

Solution

Is it possible to reference primitive-types from an array for casting?

No.

In Java, you can't treat an array of one primitive type as if it was an array of a different primitive type. So whatever the base type of the xyz array is, that is the only way you can view the elements.

The best you can do is extract an element and then explicitly cast it.

(Reflection won't help I think because the reflective APIs don't do casting of primitive types.)


What is the best practice?

This kind of low level stuff is best avoided. But if you have to do it, accept the fact that the code is inevitably going to be a bit clunky.

Best practice is therefore to hide the clunkiness inside a method so that you don't need to do this kind of thing throughout your code.

OTHER TIPS

You could do this through reflection, but it's very verbose and inefficient in Java.

The best way to accomplish this is to dispense with primatives and use the object wrapper classes. Then you can just serialize them polymorphically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top