-
Notifications
You must be signed in to change notification settings - Fork 0
Custom factories
Alexander Chapchuk edited this page Jun 30, 2021
·
4 revisions
When you registration your CustomItemStack, for default Library used default factory. Sometimes need an inject dependency into your CustomItem.
For example take CustomItemStack (MyItemStack
):
@CustomItem(type = Material.BARRIER, customModelData = 10)
public class MyItemStack extends AbstractCustomItemStack {
public MyItemStack(@NotNull ItemStack stack, Localisation messages) throws IllegalArgumentException {
super(stack);
var meta = this.getItemMeta();
meta.setDisplayName(messages.getMessageForMyItemStack());
this.setItemMeta(meta);
}
}
Let's see in construction exists external class of Localisation
. What to do next, if we want auto created of this class?
- Add optional parameter
defaultFactory
toCustomItem
annotation, like:
@CustomItem(type = Material.BARRIER, customModelData = 10, defaultFactory = false)
defaultFactory = false
means CustomItemsCore not be include this class automatically.
- Register CustomFactory.
CustomItemStackManager manager = customItemStackPlugin.getCustomItemsApi().getCustomItemStackManager();
manager.registerCustomItemStack(MyItemStack.class, new CustomItemStackFactory() {
@Override
public AbstractCustomItemStack build(CustomItemStackManager customItemStackManager, ItemStack itemStack) {
return new MyItemStack(itemStack, new LocalisationImpl());
}
});
Well done, now your Item will be creating automatically with your dependency!
CustomFactory with Guice
:
Non production code...
new CustomItemStackFactory() {
@Override
public AbstractCustomItemStack build(CustomItemStackManager customItemStackManager, ItemStack itemStack) {
var itemClazz = customItemStackManager.getCustomItemStackClass(itemStack); //Get CustomItemStack class of ItemStack
var constructor = itemClazz.getDeclaredConstructors()[0];
var constructorParameters = constructor.getParameters();
var parameters = new Object[constructorParameters.length];
parameters[0] = itemStack;
for (int i = 1; i < constructorParameters.length; i++) {
parameters[i] = injector.getInstance(constructorParameters[i].getType());
}
// Handle exception's
return (AbstractCustomItemStack) constructor.newInstance(parameters);
}
})