How to create C style union in java?

Tags: ,



I have to convert one of my code segment from C to java. Code is given below.

union commandString{
    char commndStr[20];
    struct{
        char commnd[4];
        char separator1;
        char agr1[5];
        char separator2;
        char arg2[3];
        char separator3;
        char additionalArg[5];
    };
};

I don’t want to use any explicit parser or I do not want to use

System.arraycopy

method. Is there any way to do that in my preferred way?

Answer

The best library for doing Struct and Union would be Javolutions which has been around for many years. These were designed to do this.

I suggest if you are going to use these Unsafe you wrap it up in a library which abstracts it away. This can avoid continuously running into bugs which crash your JVM (and I mean crash in the sense a C programmer would understand)

I have a library called Java-Lang which allows you to do the sort of things Java doesn’t normally allow such as 63 bit sized off heap and memory mapped, thread safe off heap operations, sharing of memory between JVM on the same machine. And as I said, I use my own library to abstract away use of Unsafe.



Source: stackoverflow