Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:net.mojodna.searchable.SearchableBeanUtils.java

/**
 * Gets the name of the property containing the bean's id.
 * //ww  w .j a  v a2  s  .c om
 * @param clazz Class to reflect on.
 * @return Name of the id property.
 */
public static String getIdPropertyName(final Class<? extends Searchable> clazz) {
    // look for Searchable.ID annotation
    final PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(clazz);
    for (final PropertyDescriptor descriptor : pds) {
        if (null != descriptor && null != descriptor.getReadMethod()
                && descriptor.getReadMethod().isAnnotationPresent(Searchable.ID.class)) {
            return descriptor.getName();
        }
    }

    return SearchableBeanUtils.ID_PROPERTY_NAME;
}

From source file:de.alpharogroup.lang.object.MergeObjectExtensions.java

/**
 * Merge the given property to the given 'to' object with the given 'with' object.
 *
 * @param <TO>/*from w w  w  .  j  av a2 s  .  c  o  m*/
 *            the generic type of the object to merge in
 * @param <WITH>
 *            the generic type of the object to merge with
 * @param toObject
 *            the object to merge in
 * @param withObject
 *            the object to merge with
 * @param propertyDescriptor
 *            the property descriptor
 * @throws InvocationTargetException
 *             if the property accessor method throws an exception
 * @throws IllegalAccessException
 *             if the caller does not have access to the property accessor method
 */
public static final <TO, WITH> void mergeProperty(final TO toObject, final WITH withObject,
        final PropertyDescriptor propertyDescriptor) throws IllegalAccessException, InvocationTargetException {
    if (PropertyUtils.isReadable(toObject, propertyDescriptor.getName())
            && PropertyUtils.isWriteable(toObject, propertyDescriptor.getName())) {
        final Method getter = propertyDescriptor.getReadMethod();
        final Object value = getter.invoke(withObject);
        if (!value.isDefaultValue()) {
            final Method setter = propertyDescriptor.getWriteMethod();
            setter.invoke(toObject, value);
        }
    }
}

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

/**
 * ?//  w w w. java2 s. c om
 * 
 * @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.afeng.common.utils.reflection.MyBeanUtils.java

public static void copyBean2Map(Map map, Object bean) {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
    for (int i = 0; i < pds.length; i++) {
        PropertyDescriptor pd = pds[i];
        String propname = pd.getName();
        try {//from   ww  w  . jav a 2s. c  om
            Object propvalue = PropertyUtils.getSimpleProperty(bean, propname);
            map.put(propname, propvalue);
        } catch (IllegalAccessException e) {
            //e.printStackTrace();
        } catch (InvocationTargetException e) {
            //e.printStackTrace();
        } catch (NoSuchMethodException e) {
            //e.printStackTrace();
        }
    }
}

From source file:io.github.moosbusch.lumpi.util.FormUtil.java

public static Map<String, Class<?>> getPropertyTypesMap(final Class<?> type,
        Map<String, Set<Class<?>>> excludedProperties) {
    final Map<String, Class<?>> result = new HashMap<>();
    PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(type);
    Map<String, Set<Class<?>>> excludedProps = excludedProperties;

    if (excludedProps != null) {
        for (PropertyDescriptor propDesc : propDescs) {
            Class<?> propertyType = propDesc.getPropertyType();

            if (propertyType != null) {
                String propertyName = propDesc.getName();

                if (excludedProps.containsKey(propertyName)) {
                    Set<Class<?>> ignoredPropertyTypes = excludedProps.get(propertyName);

                    if (!ignoredPropertyTypes.contains(type)) {
                        Set<Class<?>> superTypes = LumpiUtil.getSuperTypes(type, false, true, true);

                        for (Class<?> superType : superTypes) {
                            if (ignoredPropertyTypes.contains(superType)) {
                                result.put(propertyName, propertyType);
                                break;
                            }//from   www  .j  a va 2 s. c o  m
                        }
                    }

                }
            }
        }
    }

    return result;
}

From source file:com.aw.support.beans.BeanUtils.java

public static int countPropertyFilled(Object bean) {
    BeanWrapper wrap = new BeanWrapperImpl(bean);
    int count = 0;
    for (PropertyDescriptor descriptor : wrap.getPropertyDescriptors()) {
        if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null)
            continue;
        Object value = wrap.getPropertyValue(descriptor.getName());
        if (value instanceof String) {
            if (StringUtils.hasText((String) value))
                count++;//  w  w  w  . j  a v  a2  s.  c o  m
        } else if (value != null)
            count++;
    }
    return count;
}

From source file:com.ebay.pulsar.analytics.dao.service.BaseDBService.java

public static Map<String, Object> describe(Object obj) {
    if (obj == null) {
        return null;
    }/*  ww  w  .jav  a  2s .  co m*/
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (!key.equals("class")) {
                try {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    if (value != null) {

                        if ("properties".equalsIgnoreCase(key) || "config".equalsIgnoreCase(key)) {
                            value = new SerialBlob(((String) value).getBytes());
                        }
                        map.put(key, value);
                    }
                } catch (Exception e) {
                    logger.error("transBean1Map Error " + e);
                }
            }

        }
    } catch (Exception e) {
        logger.error("transBean2Map Error " + e);
    }
    return map;

}

From source file:jp.primecloud.auto.util.StringUtils.java

public static String reflectToString(Object object) {
    if (object == null) {
        return null;
    }// w w w.j a  v a 2 s  . com

    // String??
    if (object instanceof String) {
        return (String) object;
    }

    // ??
    if (object instanceof Number) {
        return object.toString();
    }

    // Boolean??
    if (object instanceof Boolean) {
        return object.toString();
    }

    // Character??
    if (object instanceof Character) {
        return object.toString();
    }

    // ???
    if (object instanceof Object[]) {
        return reflectToString(Arrays.asList((Object[]) object));
    }

    // ??
    if (object instanceof Collection<?>) {
        Iterator<?> iterator = ((Collection<?>) object).iterator();
        if (!iterator.hasNext()) {
            return "[]";
        }

        StringBuilder str = new StringBuilder();
        str.append("[");
        while (true) {
            Object object2 = iterator.next();
            str.append(reflectToString(object2));
            if (!iterator.hasNext()) {
                break;
            }
            str.append(", ");
        }
        str.append("]");
        return str.toString();
    }

    // ??
    if (object instanceof Map<?, ?>) {
        Iterator<?> iterator = ((Map<?, ?>) object).entrySet().iterator();
        if (!iterator.hasNext()) {
            return "{}";
        }

        StringBuilder str = new StringBuilder();
        str.append("{");
        while (true) {
            Object entry = iterator.next();
            str.append(reflectToString(entry));
            if (!iterator.hasNext()) {
                break;
            }
            str.append(", ");
        }
        str.append("}");
        return str.toString();
    }

    // Entry??
    if (object instanceof Entry<?, ?>) {
        Entry<?, ?> entry = (Entry<?, ?>) object;
        StringBuilder str = new StringBuilder();
        str.append(reflectToString(entry.getKey()));
        str.append("=");
        str.append(reflectToString(entry.getValue()));
        return str.toString();
    }

    // toString?????
    try {
        Method method = object.getClass().getMethod("toString");
        if (!Object.class.equals(method.getDeclaringClass())) {
            return object.toString();
        }
    } catch (NoSuchMethodException ignore) {
    }

    // ?????
    try {
        PropertyDescriptor[] descriptors = Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors();
        StringBuilder str = new StringBuilder();
        str.append("[");
        for (PropertyDescriptor descriptor : descriptors) {
            if ("class".equals(descriptor.getName())) {
                continue;
            }

            Method readMethod = descriptor.getReadMethod();
            if (readMethod == null) {
                continue;
            }

            if (str.length() > 1) {
                str.append(", ");
            }
            Object object2 = readMethod.invoke(object);
            str.append(descriptor.getName()).append("=").append(reflectToString(object2));
        }
        str.append("]");
        return str.toString();
    } catch (IntrospectionException ignore) {
    } catch (InvocationTargetException ignore) {
    } catch (IllegalAccessException ignore) {
    }

    // ????????commons-lang?
    return ReflectionToStringBuilder.toString(object);
}

From source file:net.openkoncept.vroom.VroomUtilities.java

public static JSONObject convertObjectToJSONObject(Object object) throws JSONException {
    JSONObject jo = new JSONObject();
    if (object instanceof Character || object instanceof String || object instanceof Boolean
            || object instanceof Short || object instanceof Integer || object instanceof Long
            || object instanceof Float || object instanceof Double || object instanceof java.util.Date
            || object instanceof java.math.BigDecimal || object instanceof java.math.BigInteger) {
        jo.put("value", getValueForJSONObject(object));
    } else if (object instanceof java.util.Map) {
        Map m = (Map) object;
        Iterator iter = m.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            jo.put(key, getValueForJSONObject(m.get(key)));
        }/*from   w ww.  j  av a2  s.c  o m*/
    } else if (object instanceof Collection) {
        Collection c = (Collection) object;
        Iterator iter = c.iterator();
        JSONArray ja = new JSONArray();
        while (iter.hasNext()) {
            ja.put(getValueForJSONObject(iter.next()));
        }
        jo.put("array", ja);
    } else if (object != null && object.getClass().isArray()) {
        Object[] oa = (Object[]) object;
        JSONArray ja = new JSONArray();
        for (int i = 0; i < oa.length; i++) {
            ja.put(getValueForJSONObject(oa[i]));
        }
        jo.put("array", ja);
    } else if (object instanceof ResourceBundle) {
        ResourceBundle rb = (ResourceBundle) object;
        Enumeration e = rb.getKeys();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            Object value = getValueForJSONObject(rb.getObject(key));
            jo.put(key, value);
        }
    } else if (object != null) {
        Class clazz = object.getClass();
        PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(object);
        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            String name = pd.getName();
            if (!"class".equals(name) && PropertyUtils.isReadable(object, pd.getName())) {
                try {
                    Object value = PropertyUtils.getProperty(object, name);
                    jo.put(name, getValueForJSONObject(value));
                } catch (Exception e) {
                    // Useless...
                }
            }
        }
    } else {
        jo.put("value", "");
    }
    return jo;
}

From source file:com.hack23.cia.service.data.impl.util.LoadHelper.java

/**
 * Inits the proxy and collections.//w w  w . jav a  2s.  c  o m
 *
 * @param obj
 *            the obj
 * @param properties
 *            the properties
 * @param dejaVu
 *            the deja vu
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws NoSuchMethodException
 *             the no such method exception
 */
private static void initProxyAndCollections(final Object obj, final PropertyDescriptor[] properties,
        final Set<Object> dejaVu)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    for (final PropertyDescriptor propertyDescriptor : properties) {

        if (PropertyUtils.getReadMethod(propertyDescriptor) != null) {

            final Object origProp = PropertyUtils.getProperty(obj, propertyDescriptor.getName());

            if (origProp != null) {
                recursiveInitialize(origProp, dejaVu);
            }
            if (origProp instanceof Collection) {
                for (final Object item : (Collection<?>) origProp) {
                    recursiveInitialize(item, dejaVu);
                }
            }
        }
    }
}