Last active
February 1, 2024 18:41
-
-
Save 2stinkysocks/21e3317c877fbc0b459ee2d6b78cb764 to your computer and use it in GitHub Desktop.
A Bukkit PersistentDataType for Java Lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.bukkit.persistence.PersistentDataAdapterContext; | |
import org.bukkit.persistence.PersistentDataType; | |
import org.bukkit.util.io.BukkitObjectInputStream; | |
import org.bukkit.util.io.BukkitObjectOutputStream; | |
import org.jetbrains.annotations.NotNull; | |
import java.io.*; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class ListDataType implements PersistentDataType<byte[], List> { | |
@NotNull | |
@Override | |
public Class<byte[]> getPrimitiveType() { | |
return byte[].class; | |
} | |
@NotNull | |
@Override | |
public Class<List> getComplexType() { | |
return List.class; | |
} | |
@NotNull | |
@Override | |
public byte[] toPrimitive(@NotNull List complex, @NotNull PersistentDataAdapterContext context) { | |
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); BukkitObjectOutputStream oos = new BukkitObjectOutputStream(bos)) { | |
oos.writeObject(complex); | |
return bos.toByteArray(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return new byte[0]; | |
} | |
} | |
@NotNull | |
@Override | |
public List fromPrimitive(@NotNull byte[] primitive, @NotNull PersistentDataAdapterContext context) { | |
try (ByteArrayInputStream bis = new ByteArrayInputStream(primitive); | |
BukkitObjectInputStream ois = new BukkitObjectInputStream(bis)) { | |
return (List) ois.readObject(); | |
} catch(IOException | ClassNotFoundException e) { | |
e.printStackTrace(); | |
return new ArrayList(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment