How to create C style union in java?

The Java language does not support unions or direct control memory layout the way that languages like C do directly.

However Oracle does offer a backdoor that was added in Java 5 that can be used by using the class sun.misc.Unsafe. It takes a bit of work, the full details have been documented by Martin Thompson on his blog.

The other option would be to write it in C and access it from Java as native functions via JNI.


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.

Tags:

C

Java