1

I have an interface Calculator which shapes a class that computes some results and returns them with a given schema.

interface Calculator {
    List<Object> getResults();
    List<String> schema();
}

Each of its subclasses has a different schema, as they do not compute exactly the same things. But all instances of a same subclass have the same schema since it computes the same way everytime.

The problem is that I want to access that schema somewhere else in my code without having to compute anything, as computations can be expensive.

Ideally, I would like that each subclass have its own public static final List<String> SCHEMA attribute. But since static attributes/methods cannot be overriden, I cannot require that all subclasses of the Calculator interface implement it.

Is there a way around, or must I store the schema when I compute the results, and pass this schema around for later use? (this can become tedious I guess)

Baptiste Merliot
  • 841
  • 11
  • 24

1 Answers1

1

For string constants you could use a runtime class annotation for the schema, and a runtime check:

default List<String> schema() {
    Schema schema = getClass().getAnnotation(Schema.class);
    if (schema == null) {
        throw new IllegalStateException("Class is missing @Schema annotation: "
            + getClass().getName());
    }
    return schema.getValues();
}

@Schema({"e", "pi", "i"})
public class ScientificCalculator implements Calculator { ... }

More dynamic things could be done with overriding schema().

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Seems to be a quite smart solution, but my first thought is : what if someone can modify it and thus it is not static & final? I found [this answer](https://stackoverflow.com/questions/14268981/modify-a-class-definitions-annotation-string-parameter-at-runtime) – Baptiste Merliot Oct 23 '18 at 15:56
  • 1
    If yes I'll use tsolakp's solution since I do not want to complicate my code too much, and my class design has some flaws anyway, I may change it. But class annotation seems to be a very interesting solution, I'll dig more into it. – Baptiste Merliot Oct 23 '18 at 16:02