Created
September 20, 2022 20:02
-
-
Save WizardlyBump17/0be4a4e57f82884abeebe82495aec62a to your computer and use it in GitHub Desktop.
makes it possible to use almost any object in the PersistentDataContainer API
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
PersistentDataContainer container = /*your container*/; | |
container.set(KEY, SerializableDataType.INSTANCE, new Location(Bukkit.getWorld("world"), 0, 64, 0)); | |
container.set(KEY, SerializableDataType.INSTANCE, Map.of("test key", "test value")); |
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.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
public class SerializableDataType implements PersistentDataType<byte[], Object> { | |
public static final SerializableDataType INSTANCE = new SerializableDataType(); | |
@NotNull | |
@Override | |
public Class<byte[]> getPrimitiveType() { | |
return byte[].class; | |
} | |
@NotNull | |
@Override | |
public Class<Object> getComplexType() { | |
return Object.class; | |
} | |
@Override | |
public byte[] toPrimitive(@NotNull Object o, @NotNull PersistentDataAdapterContext persistentDataAdapterContext) { | |
try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); | |
BukkitObjectOutputStream objectStream = new BukkitObjectOutputStream(byteStream)) { | |
objectStream.writeObject(o); | |
return byteStream.toByteArray(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return new byte[0]; | |
} | |
} | |
@NotNull | |
@Override | |
public Object fromPrimitive(@NotNull byte[] o, @NotNull PersistentDataAdapterContext persistentDataAdapterContext) { | |
try (ByteArrayInputStream byteStream = new ByteArrayInputStream(o); | |
BukkitObjectInputStream inputStream = new BukkitObjectInputStream(byteStream)) { | |
return inputStream.readObject(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return new Object(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment