Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getReadMethod.

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:com.mycomm.dao.mydao.base.MyDaoSupport.java

/**
 * ?,hibernate???select count(o) from Xxx
 * o?BUG,hibernatejpql??sqlselect/* www  .  j  a  va2 s.  c  o m*/
 * count(field1,field2,...),count()
 *
 * @param <E>
 * @param clazz
 * @return
 */
protected static <E> String getCountField(Class<E> clazz) {
    String out = "o";
    try {
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        for (PropertyDescriptor propertydesc : propertyDescriptors) {
            Method method = propertydesc.getReadMethod();
            if (method != null && method.isAnnotationPresent(EmbeddedId.class)) {
                PropertyDescriptor[] ps = Introspector.getBeanInfo(propertydesc.getPropertyType())
                        .getPropertyDescriptors();
                out = "o." + propertydesc.getName() + "."
                        + (!ps[1].getName().equals("class") ? ps[1].getName() : ps[0].getName());
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return out;
}

From source file:org.apache.activemq.artemis.utils.uri.URISchema.java

public static String getData(List<String> ignored, Object... beans) throws Exception {
    StringBuilder sb = new StringBuilder();
    synchronized (beanUtils) {
        for (Object bean : beans) {
            if (bean != null) {
                PropertyDescriptor[] descriptors = beanUtils.getPropertyUtils().getPropertyDescriptors(bean);
                for (PropertyDescriptor descriptor : descriptors) {
                    if (descriptor.getReadMethod() != null && descriptor.getWriteMethod() != null
                            && isWriteable(descriptor, ignored)) {
                        String value = beanUtils.getProperty(bean, descriptor.getName());
                        if (value != null) {
                            sb.append("&").append(descriptor.getName()).append("=").append(value);
                        }/*from   www.  j a v a2s.co  m*/
                    }
                }
            }
        }
    }
    return sb.toString();
}

From source file:org.apache.niolex.commons.bean.BeanUtil.java

/**
 * Merge the non null properties from the source bean to the target bean.
 *
 * @param to the target bean/*from ww  w  . ja  v a 2 s  .c o  m*/
 * @param from the source bean
 * @param mergeDefault whether do we merge default numeric primitives
 * @return the target bean
 */
public static final <To, From> To merge(To to, From from, boolean mergeDefault) {
    try {
        Map<String, Method> writeMap = prepareWriteMethodMap(to.getClass());
        BeanInfo fromInfo = Introspector.getBeanInfo(from.getClass());
        // Iterate over all the attributes of from, do copy here.
        for (PropertyDescriptor descriptor : fromInfo.getPropertyDescriptors()) {
            Method readMethod = descriptor.getReadMethod();
            if (readMethod == null) {
                continue;
            }
            Method writeMethod = writeMap.get(descriptor.getName());
            if (writeMethod == null) {
                continue;
            }
            Object value = readMethod.invoke(from);
            if (value == null) {
                continue;
            }
            if (!mergeDefault && isNumericPrimitiveDefaultValue(readMethod.getReturnType(), value)) {
                continue;
            }
            // Only copy value if it's assignable, auto boxing is OK.
            if (ClassUtils.isAssignable(value.getClass(), writeMethod.getParameterTypes()[0], true)) {
                writeMethod.invoke(to, value);
            }
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to merge propeties.", e);
    }
    return to;
}

From source file:com.ace.erp.common.inject.support.InjectBaseDependencyHelper.java

/**
 * ??//from w  w w . j ava2 s .co m
 *
 * @param target
 * @param annotation
 */
private static Set<Object> findDependencies(final Object target, final Class<? extends Annotation> annotation) {

    final Set<Object> candidates = Sets.newHashSet();

    ReflectionUtils.doWithFields(target.getClass(), new ReflectionUtils.FieldCallback() {
        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            Object obj = ReflectionUtils.getField(field, target);
            candidates.add(obj);
        }
    }, new ReflectionUtils.FieldFilter() {
        @Override
        public boolean matches(Field field) {
            return field.isAnnotationPresent(annotation);
        }
    });

    ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() {
        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(method);
            PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method);
            candidates.add(ReflectionUtils.invokeMethod(descriptor.getReadMethod(), target));
        }
    }, new ReflectionUtils.MethodFilter() {
        @Override
        public boolean matches(Method method) {
            boolean hasAnnotation = false;
            hasAnnotation = method.isAnnotationPresent(annotation);
            if (!hasAnnotation) {
                return false;
            }

            boolean hasReadMethod = false;
            PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method);
            hasReadMethod = descriptor != null && descriptor.getReadMethod() != null;

            if (!hasReadMethod) {
                return false;
            }

            return true;
        }
    });

    return candidates;
}

From source file:org.psnively.scala.beans.ScalaBeanInfo.java

private static void addScalaGetter(Map<String, PropertyDescriptor> propertyDescriptors, Method readMethod) {
    String propertyName = readMethod.getName();

    PropertyDescriptor pd = propertyDescriptors.get(propertyName);
    if (pd != null && pd.getReadMethod() == null) {
        try {/*from  w w w . j  a  v  a 2 s.co  m*/
            pd.setReadMethod(readMethod);
        } catch (IntrospectionException ex) {
            logger.debug("Could not add read method [" + readMethod + "] for " + "property [" + propertyName
                    + "]: " + ex.getMessage());
        }
    } else if (pd == null) {
        try {
            pd = new PropertyDescriptor(propertyName, readMethod, null);
            propertyDescriptors.put(propertyName, pd);
        } catch (IntrospectionException ex) {
            logger.debug("Could not create new PropertyDescriptor for " + "readMethod [" + readMethod
                    + "] property [" + propertyName + "]: " + ex.getMessage());
        }
    }
}

From source file:com.nesscomputing.config.ConfigMagicDynamicMBean.java

private static Map<String, Object> toMap(Object configBean) {
    PropertyDescriptor[] props = ReflectUtils.getBeanGetters(configBean.getClass());

    Map<String, Object> result = Maps.newHashMap();

    for (PropertyDescriptor prop : props) {
        if (CONFIG_MAGIC_CALLBACKS_NAME.equals(prop.getName())) {
            continue;
        }//from w w  w  .j  av  a  2 s. c om

        try {
            result.put(prop.getName(), ObjectUtils.toString(prop.getReadMethod().invoke(configBean), null));
        } catch (Exception e) {
            LOG.error(String.format("For class %s, unable to find config property %s", configBean.getClass(),
                    prop), e);
        }
    }

    return result;
}

From source file:com.baomidou.framework.common.util.BeanUtil.java

/**
 * ?//from   w  ww . j a  v a 2s.c o m
 * 
 * @param source
 *            ?
 * @param target
 *            ?
 */
public static void copy(Object source, Object target) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");
    Class<?> actualEditable = target.getClass();
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    /*
                     * no copy null properties
                     */
                    Object value = readMethod.invoke(source);
                    if (value != null) {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:com.cloudera.csd.validation.references.components.ReflectionHelper.java

/**
 * Returns the property getter method if one exists, 'null' otherwise.
 * @param obj The object which has the property 'propertyName'
 * @param propertyName The property name, e.g., "name".
 * @return/*from w  w  w.j ava  2  s .c o m*/
 */
@Nullable
public static Method propertyGetter(Object obj, String propertyName) {
    Preconditions.checkNotNull(obj);
    Preconditions.checkNotNull(propertyName);
    try {
        PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(obj, propertyName);
        return desc.getReadMethod();
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(
                "Could not access " + propertyName + " of " + obj.getClass().getSimpleName(), e);
    } catch (InvocationTargetException e) {
        throw new IllegalStateException(
                "Could not access " + propertyName + " of " + obj.getClass().getSimpleName(), e);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException(
                "No such property " + propertyName + " for " + obj.getClass().getSimpleName(), e);
    }
}

From source file:net.solarnetwork.node.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * /*from   w w w .  j  av a 2s  .c o m*/
 * @param o
 *        the object to inspect
 * @param ignore
 *        a set of property names to ignore (optional)
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = new BeanWrapperImpl(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.utils.BeanUtils.java

/**
 * This methods performs deep comparison of two objects of the same class.
 * Comparison is performed only on properties exposed via the standard
 * JavaBean mechanism. Properties of primitive types, wrappers,
 * {@link String}, {@link CharSequence}, {@link Date}, {@link Enum} are
 * compared directly using {@link Object#equals(Object)}; other complex
 * properties are compared recursively. Elements of {@link Collection}
 * properties are iterated and compared.
 * /*ww  w. j ava  2s. com*/
 * @param <T>
 * @param obj1
 * @param obj2
 * @return
 * @throws NullPointerException
 *             if any of the parameters is null.
 */
public static <T> boolean deepCompare(T obj1, T obj2) {
    if (obj1 == obj2) {
        return true;
    }
    // if it's a "simple" object, do direct comparison.
    for (Class<?> cls : DIRECTLY_COMPARABLE_TYPES) {
        if (cls.isAssignableFrom(obj1.getClass())) {
            if (!obj1.equals(obj2)) {
                log.info("Values don't match: " + obj1 + " and " + obj2);
                System.out.println();
                System.out.println("Values don't match: " + obj1 + " and " + obj2);
                return false;
            } else {
                return true;
            }
        }
    }
    try {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj1.getClass());
        for (PropertyDescriptor pd : descriptors) {
            // ignore properties which cannot be read.
            if (pd.getReadMethod() != null) {
                Class<?> type = pd.getPropertyType();
                // this check will skip Object.getClass().
                if (SKIP_TYPES.contains(type)) {
                    continue;
                }
                String name = pd.getName();
                Object v1 = PropertyUtils.getSimpleProperty(obj1, name);
                Object v2 = PropertyUtils.getSimpleProperty(obj2, name);
                if (v1 == v2 || (v1 == null && v2 == null)) {
                    continue;
                }
                if ((v1 == null && v2 != null) || (v1 != null && v2 == null)) {
                    log.info("Values don't match: " + v1 + " and " + v2);
                    System.out.println();
                    System.out.println("Values don't match: " + v1 + " and " + v2);
                    return false;
                }
                // Collections need special handling.
                if (Collection.class.isAssignableFrom(type)) {
                    List l1 = new ArrayList((Collection) v1);
                    List l2 = new ArrayList((Collection) v2);
                    if (l1.size() != l2.size()) {
                        log.info("Collection sizes don't match:" + l1 + l2);
                        System.out.println();
                        System.out.println("Collection sizes don't match:" + l1 + ", " + l2);
                        return false;
                    }
                    for (int i = 0; i < l1.size(); i++) {
                        Object el1 = l1.get(i);
                        Object el2 = l2.get(i);
                        if (!deepCompare(el1, el2)) {
                            return false;
                        }
                    }

                } else if (!deepCompare(v1, v2)) {
                    return false;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getFullStackTrace(e));
    }
    return true;
}