io.ultreia.java4all.lang.Setters Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-lang Show documentation
Show all versions of java-lang Show documentation
Java Lang api extends by Ultreia.io (not guava, not commons)
package io.ultreia.java4all.lang;
/*-
* #%L
* Java Lang extends by Ultreia.io
* %%
* Copyright (C) 2017 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 java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.beanutils.PropertyUtils;
/**
* Created by tchemit on 25/09/17.
*
* @author Tony Chemit - [email protected]
*/
public class Setters {
/**
* Obtains all writeable properties from a given type.
*
* @param beanType the type to seek
* @return the set of all writeable properties for the given type
*/
public static Set getWriteableProperties(Class> beanType) {
Objects.requireNonNull(beanType);
Set result = new HashSet<>();
Objects2.walk(new Objects2.ClassWalkVisitor() {
@Override
public void onVisit(Class> beanType) {
for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(beanType)) {
if (Objects2.IS_WRITE_DESCRIPTOR.test(descriptor)) {
result.add(descriptor.getName());
}
}
}
@Override
public boolean canContinue() {
return true;
}
}, beanType);
return result;
}
public static Method getMutator(Object bean, String property) {
Objects.requireNonNull(bean);
Objects.requireNonNull(property);
Method mutator = null;
try {
PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, property);
if (descriptor != null) {
mutator = descriptor.getWriteMethod();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return mutator;
}
}