An open API service indexing awesome lists of open source software.

https://github.com/kilemonn/java-union

A simple union implementation in Java/Kotlin.
https://github.com/kilemonn/java-union

java-library kotlin library reflection union

Last synced: about 1 month ago
JSON representation

A simple union implementation in Java/Kotlin.

Awesome Lists containing this project

README

          

# java-union

[![CI Build](https://github.com/Kilemonn/java-union/actions/workflows/gradle.yml/badge.svg)](https://github.com/Kilemonn/java-union/actions/workflows/gradle.yml) [![Coverage](.github/badges/jacoco.svg)](https://github.com/Kilemonn/java-union/actions/workflows/gradle.yml)

A simple union implementation in Kotlin allowing you to initialise the union instance with a specific object
and re-interpret the internal byte array as different types.
The byte array cannot be interpreted as a type that is larger than the buffer.

## Quick Start

This can be included by making sure that you have [JitPack](https://jitpack.io/) setup as a dependency repository within your project.
You can refer to the hosted versions of this library at [java-union](https://jitpack.io/#Kilemonn/java-union).

```groovy
implementation("com.github.Kilemonn:union:0.1.0")
```

### Example

The below example in `Kotlin` stores a `Char` in the `Union` and reads its value out as a `Short`.

```kotlin
val char = 'c'
val union = Union(char)

// The union's size is 2 since char's are 2 bytes in the JVM
assertEquals(2, union.size)

// Will have value 99 because of 'c' having the ASCII value of 99
val asShort = union.asType(Short::class.java)
assertEquals(99, asShort)

// This will return null, since the size of an int is 4 bytes, which is larger than the current
// internal Union buffer (`union.size`)
val asInt = union.asType(Int::class.java)
assertNull(asInt)
```

### Limitations

- Currently only primitive and object primitive types will be serialised into the internal Union buffer.
- If you are serialising custom types make sure you test it properly incase there are any fields that
cannot be serialised.