mercredi 3 juillet 2019

Statically providing metadata for a class in an enforceable manner

This is a little bit of a complicated issue, but I'll do my best to explain it understandably.

To start, consider the following classes.

public abstract class Invokable {
    private String name;

    protected Invokable(String name) { ... }

    public String getName() { ... }

    public abstract void invoke();
}

public class PrintInvokable extends Invokable {
    public PrintInvokable() {
        super("print");
    }

    @Override
    public void invoke() { ... }
}

Another class, InvokerDispatcher, handles events from a messaging application and calls Invokable#invoke on an instance of the appropriate implementation based on the name field. This is all done reflectively so as to be able to scan the classpath for all the valid Invokable implementations and dynamically load them at runtime.

The issue here is that I can only access name via instance, so I have to instantiate a copy of every Invokable in order to check its name against the message content. My solution right now is to keep a list of pre-instantiated copies of each implementation in a separate class, then call a method that fetches and replaces an instance from the list by name.

I'd like to be able to do this statically, but I can't come up with a way to make it enforceable. Having a static abstract getName() in Invokable would be the easiest way to do it, but unfortunately Java doesn't support it. Any ideas?

Aucun commentaire:

Enregistrer un commentaire