Skip to content

Adapters

Mazen Kotb edited this page Jul 6, 2016 · 1 revision

ConfigAPI uses adapters as a conversion method between Java objects and YAML formats. For almost if not all cases, writing an adapter yourself would not be required. You can see all the types that are natively supported here. If there are certain object types that have to be converted manually, then you must write an adapter for it. At the moment, there is no native support for adding adapters which types have generics, they do sometimes work; use with caution. If anybody knows how native support for this could be added easily, it is highly recommended to suggest it in an issue or PR the addition.

To write an adapter, you need to implement the ObjectAdapter<I, O> class; let me walk you through what everything in the class means. Generic I is what will be used in fields, the object type you're writing the adapter for. Generic O is what will be returned to the MemorySection#set method, therefore it must be compatible with the Bukkit configuration API.

public class RandomAdapter implements ObjectAdapter<Random, Long> {
    @Override
    public Random read(String key, ConfigurationSection section) { // converting YAML object to Random
        return new Random(section.getLong(key));
    }

    @Override
    public Long write(Random obj) { // converting Random to a YAML supported object
        AtomicLong scramedSeed = InternalsHelper.getField(InternalsHelper.fieldFor(obj, "seed"), obj);
        return scramedSeed.get() ^ 0x5DEECE66DL;
    }
}

This is merely an example of how you would implement an adapter for a select object, in this case, Random. Now for obvious reasons, you wouldn't want to save a Random instance to file, it was used an example in this case. To register this adapter, you would call the AdapterHandler.registerAdapter method as follows:

AdapterHandler.registerAdapter(Random.class, new RandomAdapter());

... and that's how you write your own adapters!

Clone this wiki locally