Skip to content

Basic Usage examples

The_Fireplace edited this page Jan 24, 2022 · 1 revision

A simple example of how the custom @Implementation annotation is used:

NetworkInterface.java

public interface NetworkInterface {
    ByteBuf getBuffer();
}

BufferFactory.java

@Implementation
public class BufferFactory implements NetworkInterface {
    @Override
    public ByteBuf getBuffer() {
        // do stuff
    }
}

SomeOtherFile.java (Using Constructor Injection)

public class SomeOtherFile {
    private final NetworkInterface networkInterface;
    
    @Inject
    public SomeOtherFile(NetworkInterface interface) {
        this.networkInterface = interface;
    }
    
    public void doStuff() {
        ByteBuf buffer = this.networkInterface.getBuffer();
    }
}

DiEntrypoint.java

public class DiEntrypoint implements DIModInitializer {
    public void onInitialize(Injector diContainer) {
        SomeOtherFile otherFile = diContainer.getInstance(SomeOtherFile.class);
        otherFile.doStuff();
    }
}

@Implementation annotation with multiple interfaces:

NetworkInterface.java

public interface NetworkInterface {
    ByteBuf getBuffer();
}

BufferFactory.java

@Implementation("your.package.NetworkInterface")
public class BufferFactory implements NetworkInterface, SomeOtherInterface {
    @Override
    public ByteBuf getBuffer() {
        // do stuff
    }
}

SomeOtherFile.java (Using Constructor Injection)

public class SomeOtherFile {
    private final NetworkInterface networkInterface;
    
    @Inject
    public SomeOtherFile(NetworkInterface interface) {
        this.networkInterface = interface;
    }
    
    public void doStuff() {
        ByteBuf buffer = this.networkInterface.getBuffer();
    }
}