Skip to main content
Version: 0.2

NBT related stuff

info

Unavailable in version v0.2-beta

Object-NbtCompound conversion

In package me.ranzeplay.messagechain.nbtutils

Personally speaking, it often drives me crazy to code the conversion between NbtCompound and Object. It is basically hard-coding. So I made a small helper to do the favor.

Annotations

@NBTSerializable

Every class which needs to serialize and deserialize to and from NbtCompound should have the annotation, which indicates that the object is able to do the conversion. Often, you'll extend AbstractNBTSerializable as well, because you are using MessageChain :)

@NBTSerializationEntry(key)

Every field which needs to take part in the conversion should have the annotation. It tells the NBTHelper that it need to process the field.

Parameter
  • key A string value, whose default value is the name of the field, can be customized by yourself.

Conversion methods

NBTHelper.serialize(T)

Serializes an Object to NbtCompound.

NBTHelper.deserialize(NbtCompound, Class<T>)

Deserializes a NbtCompound to target Object.

Base types

The following types are served as base types, which you can directly annotate them with @NBTSerializationEntry without writing special serialization methods.

  • int, Integer
  • short, Short
  • long, Long
  • float, Float
  • double, Double
  • int[]
  • byte[]
  • long[]
  • boolean, Boolean
  • String
  • AbstractList as super class(like ArrayList)
  • AbstractMap as super class(like HashMap)
warning

Exceptions will be thrown if annotated an abstract class field as the converter will create an instance of class while processing.

Example

Often used combined with AbstractNBTSerializable.

Source file link

ExampleData.java
public class ExampleData extends AbstractNBTSerializable implements Cloneable {
@NBTSerializationEntry
private String message;
@NBTSerializationEntry
private boolean issueError;

@SneakyThrows
@Override
public NbtCompound toNbt() {
return NBTHelper.serialize(this.clone());
}

@Override
public void fromNbt(NbtCompound nbt) {
var result = NBTHelper.deserialize(nbt, ExampleData.class);
this.message = result.message;
this.issueError = result.issueError;
}

@Override
public Class<ExampleData> getGenericClass() {
return ExampleData.class;
}
}