io.ultreia.java4all.bean.definition.JavaBeanPropertyDefinition Maven / Gradle / Ivy
package io.ultreia.java4all.bean.definition;
/*-
* #%L
* Java Beans extends by Ultreia.io
* %%
* Copyright (C) 2018 Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import com.google.common.base.Defaults;
import io.ultreia.java4all.bean.JavaBean;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* Created by tchemit on 13/01/2018.
*
* @author Tony Chemit - [email protected]
*/
public final class JavaBeanPropertyDefinition {
private final String propertyName;
private final Class type;
private final Function getter;
private final BiConsumer setter;
private final V defaultValue;
JavaBeanPropertyDefinition(String propertyName, Class type, Function getter, BiConsumer setter) {
this.propertyName = Objects.requireNonNull(propertyName);
this.type = Objects.requireNonNull(type);
this.getter = getter;
this.setter = setter;
this.defaultValue = type.isPrimitive() ? Defaults.defaultValue(type) : null;
}
public JavaBeanPropertyDefinition checkCanRead() {
if (!canRead()) {
throw new IllegalArgumentException("Property " + propertyName + " is not readable.");
}
return this;
}
public JavaBeanPropertyDefinition checkCanWrite() {
if (!canWrite()) {
throw new IllegalArgumentException("Property " + propertyName + " is not writable.");
}
return this;
}
public String propertyName() {
return propertyName;
}
public Class> type() {
return type;
}
public Function getter() {
return getter;
}
public BiConsumer setter() {
return setter;
}
public V defaultValue() {
return defaultValue;
}
public boolean canRead() {
return getter != null;
}
public boolean canWrite() {
return setter != null;
}
public boolean canReadAndWrite() {
return canRead() && canWrite();
}
public V get(O javaBean) {
return getter.apply(javaBean);
}
public void set(O javaBean, V value) {
setter.accept(javaBean, value);
}
public void copy(O source, O target) {
V value = get(source);
set(target, value);
}
public void clear(O javaBean) {
set(javaBean, defaultValue);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy