All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.carrot2.attrs.AttrObject Maven / Gradle / Ivy

There is a newer version: 4.6.0
Show newest version
/*
 * Carrot2 project.
 *
 * Copyright (C) 2002-2021, Dawid Weiss, Stanisław Osiński.
 * All rights reserved.
 *
 * Refer to the full license file "carrot2.LICENSE"
 * in the root folder of the repository checkout or at:
 * https://www.carrot2.org/carrot2.LICENSE
 */
package org.carrot2.attrs;

import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class AttrObject extends Attr {
  private Class clazz;
  private Supplier getter;
  private Consumer setter;
  private Supplier newInstance;

  AttrObject(
      Class clazz,
      T defaultValue,
      String label,
      List> constraint,
      Supplier newInstance,
      Supplier getter,
      Consumer setter) {
    super(null, label, constraint);
    this.clazz = clazz;

    this.setter = setter != null ? setter : super::set;
    this.getter = getter != null ? getter : super::get;
    this.newInstance = newInstance;

    set(defaultValue);
  }

  public void set(T value) {
    super.set(value);
    setter.accept(value);
  }

  public  E set(E value, Consumer closure) {
    set(value);
    closure.accept(value);
    return value;
  }

  public T get() {
    return getter.get();
  }

  public Class getInterfaceClass() {
    return clazz;
  }

  public boolean isDefaultClass(Object value) {
    Objects.requireNonNull(value);
    T def = newDefaultValue();
    return def != null
        && Objects.equals(def.getClass(), value.getClass())
        && Objects.equals(clazz, value.getClass());
  }

  public T newDefaultValue() {
    return this.newInstance.get();
  }

  public static class Builder extends Attr.BuilderScaffold {
    private Class clazz;
    private Supplier getter;
    private Consumer setter;

    public Builder(Class clazz) {
      this.clazz = clazz;
    }

    public Builder getset(Supplier getter, Consumer setter) {
      this.setter = Objects.requireNonNull(setter);
      this.getter = Objects.requireNonNull(getter);
      return this;
    }

    @Override
    public Builder label(String label) {
      super.label(label);
      return this;
    }

    public AttrObject defaultValue(Supplier newInstance) {
      Objects.requireNonNull(newInstance, "New instance supplier must not be null.");
      return defaultValue(newInstance.get(), newInstance);
    }

    public AttrObject defaultValue(T defaultValue, Supplier newInstance) {
      Objects.requireNonNull(newInstance, "New instance supplier must not be null.");
      return new AttrObject(
          clazz, defaultValue, label, getConstraint(), newInstance, getter, setter);
    }
  }

  public static  Builder builder(Class clazz) {
    return new Builder<>(clazz);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy