org.fiolino.common.container.Selector Maven / Gradle / Ivy
Show all versions of commons Show documentation
package org.fiolino.common.container;
import java.util.function.Supplier;
/**
* The selector is the key in a {@link Container}. It gets registered by a corresponding {@link Schema}.
*/
public class Selector {
private final int position;
private final Schema schema;
private final Schema.Protected protection;
private boolean isInherited = true;
/**
* Constructor called from the Schema instance.
*
* @param schema The owner
* @param position Position in the container's value array
* @param protection Used to restrict write access
*/
Selector(Schema schema, int position, Schema.Protected protection) {
this.schema = schema;
this.position = position;
this.protection = protection;
}
/**
* Changes the inherited flag.
*
* When a selector is inherited, then each sub container will query its parent when there's no
* local value available. If this is set to false, then only local values will be returned
* by calling get().
*/
public Selector setInherited(boolean isInherited) {
this.isInherited = isInherited;
return this;
}
final int getPosition() {
return position;
}
void validateOwner(Schema toCheck) {
if (toCheck != schema) {
throw new IllegalStateException("Cannot work with " + this + " on " + toCheck);
}
}
/**
* Gets a value from a given {@link Container}.
*/
public T get(Container container) {
return container.get(this);
}
Object getDirectlyFromParent(Container parent) {
return isInherited ? parent.getDirectly(this) : null;
}
/**
* Assigns a value.
*/
public void set(Container container, T value) {
container.set(this, value);
}
void checkWriteAccess(Supplier