net.dongliu.commons.bean.BeanMap Maven / Gradle / Ivy
package net.dongliu.commons.bean;
import net.dongliu.commons.collection.Iterators;
import net.dongliu.commons.collection.MoreCollections;
import net.dongliu.commons.collection.Pair;
import net.dongliu.commons.concurrent.WeakCache;
import net.dongliu.commons.exception.Throwables;
import javax.annotation.Nonnull;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* Wrap bean as immutable map
*
* @author Liu Dong
*/
class BeanMap implements Map {
private final Object bean;
private final Map map;
private static final WeakCache, Map> cache =
WeakCache.create(BeanMap::getPropertyMap);
public BeanMap(Object bean) {
this.bean = Objects.requireNonNull(bean);
this.map = cache.get(bean.getClass());
}
@Nonnull
private static Map getPropertyMap(Class> cls) {
Map map = new HashMap<>();
for (PropertyDescriptor descriptor : Beans.getProperties(cls)) {
if (descriptor.getReadMethod() != null) {
String name = descriptor.getName();
map.put(name, descriptor);
}
}
return map;
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
for (String key : map.keySet()) {
PropertyDescriptor descriptor = map.get(key);
Object v = getValue(descriptor);
if (Objects.equals(value, v)) {
return true;
}
}
return false;
}
private Object getValue(PropertyDescriptor descriptor) {
try {
return descriptor.getReadMethod().invoke(bean);
} catch (IllegalAccessException | InvocationTargetException e) {
throw Throwables.throwAny(e);
}
}
@Override
public Object get(Object key) {
PropertyDescriptor descriptor = map.get(key);
if (descriptor == null) {
return null;
}
return getValue(descriptor);
}
@Override
public Object put(String key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map extends String, ?> m) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
@Nonnull
public Set keySet() {
return map.keySet();
}
@Override
@Nonnull
public Collection
© 2015 - 2025 Weber Informatics LLC | Privacy Policy