Java Code Examples for java.beans.PropertyDescriptor#getReadMethod()

The following examples show how to use java.beans.PropertyDescriptor#getReadMethod() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: webtau   File: JavaBeanUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Map<String, ?> extractMap(Object bean) throws IntrospectionException,
        InvocationTargetException,
        IllegalAccessException {
    LinkedHashMap<String, Object> result = new LinkedHashMap<>();

    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
    PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor property : properties) {
        Method readMethod = property.getReadMethod();
        if (!property.getName().equals("class") && readMethod != null) {
            result.put(property.getName(), readMethod.invoke(bean));
        }
    }

    return result;
}
 
Example 2
Source Project: waterdrop   File: ConfigBeanImpl.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean hasAtLeastOneBeanProperty(Class<?> clazz) {
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        return false;
    }

    for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
        if (beanProp.getReadMethod() != null && beanProp.getWriteMethod() != null) {
            return true;
        }
    }

    return false;
}
 
Example 3
Source Project: knox   File: XmlUrlRewriteRulesExporter.java    License: Apache License 2.0 6 votes vote down vote up
private Element createElement( Document document, String name, Object bean )
    throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
  Element element = document.createElement( name );
  BeanInfo beanInfo = Introspector.getBeanInfo( bean.getClass(), Object.class );
  for( PropertyDescriptor propInfo: beanInfo.getPropertyDescriptors() ) {
    String propName = propInfo.getName();
    if( propInfo.getReadMethod() != null && String.class.isAssignableFrom( propInfo.getPropertyType() ) ) {
      String propValue = BeanUtils.getProperty( bean, propName );
      if( propValue != null && !propValue.isEmpty() ) {
        // Doing it the hard way to avoid having the &'s in the query string escaped at &amp;
        Attr attr = document.createAttribute( propName );
        attr.setValue( propValue );
        element.setAttributeNode( attr );
        //element.setAttribute( propName, propValue );
      }
    }
  }
  return element;
}
 
Example 4
private static boolean hasAtLeastOneBeanProperty(Class<?> clazz) {
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        return false;
    }

    for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
        if (beanProp.getReadMethod() != null && beanProp.getWriteMethod() != null) {
            return true;
        }
    }

    return false;
}
 
Example 5
public static boolean hasPD(PropertyDescriptor pd) {
    if (null == pd.getPropertyType()) {
        return false;
    }
    return (null != pd.getReadMethod())
        || (null != pd.getWriteMethod());
}
 
Example 6
private static void test(Class type) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, "prop");
    if (pd instanceof IndexedPropertyDescriptor) {
        error(pd, type.getSimpleName() + ".prop should not be an indexed property");
    }
    if (!pd.getPropertyType().equals(Color.class)) {
        error(pd, type.getSimpleName() + ".prop type should be a Color");
    }
    if (null == pd.getReadMethod()) {
        error(pd, type.getSimpleName() + ".prop should have classic read method");
    }
    if (null == pd.getWriteMethod()) {
        error(pd, type.getSimpleName() + ".prop should have classic write method");
    }
}
 
Example 7
Source Project: hottub   File: Test4619536.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean hasPD(PropertyDescriptor pd) {
    if (null == pd.getPropertyType()) {
        return false;
    }
    return (null != pd.getReadMethod())
        || (null != pd.getWriteMethod());
}
 
Example 8
Source Project: WebStack-Guns   File: Contrast.java    License: MIT License 5 votes vote down vote up
/**
 * 比较两个对象,并返回不一致的信息
 *
 * @author stylefeng
 * @Date 2017/5/9 19:34
 */
public static String contrastObj(Object pojo1, Object pojo2) {
    String str = "";
    try {
        Class clazz = pojo1.getClass();
        Field[] fields = pojo1.getClass().getDeclaredFields();
        int i = 1;
        for (Field field : fields) {
            if ("serialVersionUID".equals(field.getName())) {
                continue;
            }
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            Method getMethod = pd.getReadMethod();
            Object o1 = getMethod.invoke(pojo1);
            Object o2 = getMethod.invoke(pojo2);
            if (o1 == null || o2 == null) {
                continue;
            }
            if (o1 instanceof Date) {
                o1 = DateUtil.formatDate((Date) o1);
            }
            if (!o1.toString().equals(o2.toString())) {
                if (i != 1) {
                    str += separator;
                }
                str += "字段名称" + field.getName() + ",旧值:" + o1 + ",新值:" + o2;
                i++;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return str;
}
 
Example 9
private static void test(Class type) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, "prop");
    if (pd instanceof IndexedPropertyDescriptor) {
        error(pd, type.getSimpleName() + ".prop should not be an indexed property");
    }
    if (!pd.getPropertyType().equals(Color.class)) {
        error(pd, type.getSimpleName() + ".prop type should be a Color");
    }
    if (null == pd.getReadMethod()) {
        error(pd, type.getSimpleName() + ".prop should have classic read method");
    }
    if (null == pd.getWriteMethod()) {
        error(pd, type.getSimpleName() + ".prop should have classic write method");
    }
}
 
Example 10
Source Project: onetwo   File: ReflectUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Method getReadMethod(Class objClass, PropertyDescriptor pd) {
		Method readMethod;
//		if (Serializable.class.equals(pd.getPropertyType())) {
		if (pd.getReadMethod()==null || pd.getReadMethod().isBridge()) {
			readMethod = getReadMethod(objClass, pd.getName(), pd.getPropertyType());
		} else {
			readMethod = pd.getReadMethod();
		}
		return readMethod;
	}
 
Example 11
/**
 * @see net.sf.jasperreports.engine.JRDataSourceProvider#getFields(net.sf.jasperreports.engine.JasperReport)
 */
@Override
public JRField[] getFields(JasperReport report) throws JRException {
	BeanInfo beanInfo = null;

	try {
		beanInfo = Introspector.getBeanInfo(beanClass);
	} catch (IntrospectionException e) {
		throw new JRException(e);
	}

	PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
	if(descriptors != null) 
	{
		ArrayList<JRField> fields = new ArrayList<JRField>(descriptors.length);
		
		for (int i = 0; i < descriptors.length; i++) {
			PropertyDescriptor descriptor = descriptors[i];
			
			if (!(descriptor instanceof IndexedPropertyDescriptor) && descriptor.getReadMethod() != null) 
			{
				JRDesignField field = new JRDesignField();
				field.setValueClassName(normalizeClass(descriptor.getPropertyType()).getCanonicalName());
				field.setName(descriptor.getName());
				
				fields.add(field);
			}
		}

		return fields.toArray(new JRField[fields.size()]);
	}

	return new JRField[0];
}
 
Example 12
Source Project: lams   File: BeanUtils.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copy the property values of the given source bean into the given target bean.
 * <p>Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * @param source the source bean
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)
		throws BeansException {

	Assert.notNull(source, "Source must not be null");
	Assert.notNull(target, "Target must not be null");

	Class<?> actualEditable = target.getClass();
	if (editable != null) {
		if (!editable.isInstance(target)) {
			throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
					"] not assignable to Editable class [" + editable.getName() + "]");
		}
		actualEditable = editable;
	}
	PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
	List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

	for (PropertyDescriptor targetPd : targetPds) {
		Method writeMethod = targetPd.getWriteMethod();
		if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
			PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
			if (sourcePd != null) {
				Method readMethod = sourcePd.getReadMethod();
				if (readMethod != null &&
						ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
					try {
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
							writeMethod.setAccessible(true);
						}
						writeMethod.invoke(target, value);
					}
					catch (Throwable ex) {
						throw new FatalBeanException(
								"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
					}
				}
			}
		}
	}
}
 
Example 13
public BeanPropertyHandler(PropertyDescriptor pd) {
	super(pd.getPropertyType(), pd.getReadMethod() != null, pd.getWriteMethod() != null);
	this.pd = pd;
}
 
Example 14
Source Project: submarine   File: DictAnnotation.java    License: Apache License 2.0 4 votes vote down vote up
private static Object mergeDictText(Object object, Map<String, List<SysDictItem>> mapDictItems)
    throws Exception {
  // Map<Field->Value>
  HashMap<String, Object> mapFieldValues = new HashMap<>();
  //  Map<Field->FieldType>
  HashMap<String, Object> mapFieldAndType = new HashMap<>();

  Class<? extends Object> objectClass = object.getClass();
  BeanInfo beanInfo = Introspector.getBeanInfo(objectClass);
  PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  // Get data that already exists in the object
  for (int i = 0; i < propertyDescriptors.length; i++) {
    PropertyDescriptor descriptor = propertyDescriptors[i];
    String propertyName = descriptor.getName();
    if (!propertyName.equals("class")) {
      Method readMethod = descriptor.getReadMethod();
      if (null == readMethod) {
        throw new Exception("Can not found " + propertyName + " ReadMethod(), All fields in "
            + objectClass.getName() + " need add set and set methods.");
      }
      Object result = readMethod.invoke(object, new Object[0]);
      mapFieldValues.put(propertyName, result);
      mapFieldAndType.put(propertyName, descriptor.getPropertyType());

      if (mapDictItems.containsKey(propertyName)) {
        // add new dict text field to object
        mapFieldAndType.put(propertyName + DICT_SUFFIX, String.class);

        List<SysDictItem> dictItems = mapDictItems.get(propertyName);
        for (SysDictItem dictItem : dictItems) {
          if (StringUtils.equals(String.valueOf(result), dictItem.getItemCode())) {
            mapFieldValues.put(propertyName + DICT_SUFFIX, dictItem.getItemName());
            break;
          }
        }
      }
    }
  }

  // Map to entity object
  DictAnnotation bean = new DictAnnotation(mapFieldAndType);
  Set<String> keys = mapFieldAndType.keySet();
  for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
    String key = it.next();
    bean.setValue(key, mapFieldValues.get(key));
  }

  Object newObj = bean.getObject();
  return newObj;
}
 
Example 15
Source Project: aws-sdk-java-v2   File: BeanTableSchema.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean isMappableProperty(PropertyDescriptor propertyDescriptor) {
    return propertyDescriptor.getReadMethod() != null
        && propertyDescriptor.getWriteMethod() != null
        && getPropertyAnnotation(propertyDescriptor, DynamoDbIgnore.class) == null;
}
 
Example 16
Source Project: kylin   File: BeanValidator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Tests the get/set methods of the specified class.
 */
public static <T> void validateAccssor(final Class<T> clazz, final String... skipThese)
        throws IntrospectionException {
    final PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {

        for (String skipThis : skipThese) {
            if (skipThis.equals(prop.getName())) {
                continue;
            }
        }

        findBooleanIsMethods(clazz, prop);

        final Method getter = prop.getReadMethod();
        final Method setter = prop.getWriteMethod();

        if (getter != null && setter != null) {
            final Class<?> returnType = getter.getReturnType();
            final Class<?>[] params = setter.getParameterTypes();

            if (params.length == 1 && params[0] == returnType) {
                try {
                    Object value = buildValue(returnType);

                    T bean = clazz.getDeclaredConstructor().newInstance();

                    setter.invoke(bean, value);

                    Assert.assertEquals(
                            String.format(Locale.ROOT, "Failed while testing property %s", prop.getName()), value,
                            getter.invoke(bean));

                } catch (Exception ex) {
                    ex.printStackTrace();
                    System.err.println(
                            String.format(Locale.ROOT, "An exception was thrown while testing the property %s: %s",
                                    prop.getName(), ex.toString()));
                }
            }
        }
    }
}
 
Example 17
/**
 * Iterate through all properties on the MBean class and gives subclasses
 * the chance to vote on the inclusion of both the accessor and mutator.
 * If a particular accessor or mutator is voted for inclusion, the appropriate
 * metadata is assembled and passed to the subclass for descriptor population.
 * @param managedBean the bean instance (might be an AOP proxy)
 * @param beanKey the key associated with the MBean in the beans map
 * of the {@code MBeanExporter}
 * @return the attribute metadata
 * @throws JMException in case of errors
 * @see #populateAttributeDescriptor
 */
@Override
protected ModelMBeanAttributeInfo[] getAttributeInfo(Object managedBean, String beanKey) throws JMException {
	PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(getClassToExpose(managedBean));
	List<ModelMBeanAttributeInfo> infos = new ArrayList<ModelMBeanAttributeInfo>();

	for (PropertyDescriptor prop : props) {
		Method getter = prop.getReadMethod();
		if (getter != null && getter.getDeclaringClass() == Object.class) {
			continue;
		}
		if (getter != null && !includeReadAttribute(getter, beanKey)) {
			getter = null;
		}

		Method setter = prop.getWriteMethod();
		if (setter != null && !includeWriteAttribute(setter, beanKey)) {
			setter = null;
		}

		if (getter != null || setter != null) {
			// If both getter and setter are null, then this does not need exposing.
			String attrName = JmxUtils.getAttributeName(prop, isUseStrictCasing());
			String description = getAttributeDescription(prop, beanKey);
			ModelMBeanAttributeInfo info = new ModelMBeanAttributeInfo(attrName, description, getter, setter);

			Descriptor desc = info.getDescriptor();
			if (getter != null) {
				desc.setField(FIELD_GET_METHOD, getter.getName());
			}
			if (setter != null) {
				desc.setField(FIELD_SET_METHOD, setter.getName());
			}

			populateAttributeDescriptor(desc, getter, setter, beanKey);
			info.setDescriptor(desc);
			infos.add(info);
		}
	}

	return infos.toArray(new ModelMBeanAttributeInfo[infos.size()]);
}
 
Example 18
@Override
protected BeanInfo instantiate(Class<?> type, String prefix, String name) {
    if (DEFAULT.equals(prefix)) {
        prefix = DEFAULT_NEW;
    }
    // this optimization will only use the BeanInfo search path
    // if is has changed from the original
    // or trying to get the ComponentBeanInfo
    BeanInfo info = !DEFAULT_NEW.equals(prefix) || "ComponentBeanInfo".equals(name)
            ? super.instantiate(type, prefix, name)
            : null;

    if (info != null) {
        // make sure that the returned BeanInfo matches the class
        BeanDescriptor bd = info.getBeanDescriptor();
        if (bd != null) {
            if (type.equals(bd.getBeanClass())) {
                return info;
            }
        }
        else {
            PropertyDescriptor[] pds = info.getPropertyDescriptors();
            if (pds != null) {
                for (PropertyDescriptor pd : pds) {
                    Method method = pd.getReadMethod();
                    if (method == null) {
                        method = pd.getWriteMethod();
                    }
                    if (isValid(type, method)) {
                        return info;
                    }
                }
            }
            else {
                MethodDescriptor[] mds = info.getMethodDescriptors();
                if (mds != null) {
                    for (MethodDescriptor md : mds) {
                        if (isValid(type, md.getMethod())) {
                            return info;
                        }
                    }
                }
            }
        }
    }
    return null;
}
 
Example 19
Source Project: zooadmin   File: BeanMapUtil.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map bean2Map(Object bean) throws IntrospectionException,
		IllegalAccessException, InvocationTargetException {
	Class type = bean.getClass();
	Map returnMap = new HashMap();
	BeanInfo beanInfo = Introspector.getBeanInfo(type);
	PropertyDescriptor[] propertyDescriptors = beanInfo
			.getPropertyDescriptors();
	for (int i = 0; i < propertyDescriptors.length; i++) {
		PropertyDescriptor descriptor = propertyDescriptors[i];
		String propertyName = descriptor.getName();
		if (!propertyName.equals("class")) {
			Method readMethod = descriptor.getReadMethod();
			Object result = readMethod.invoke(bean, new Object[0]);
			// System.out.println(descriptor.getName()+"---"+descriptor.getPropertyType().getSimpleName());
			if (result != null) {
				returnMap.put(propertyName, result);
			} else {
				switch (descriptor.getPropertyType().getSimpleName()) {
				case "String":
					returnMap.put(propertyName, "");
					break;
				case "Integer":
					returnMap.put(propertyName, 0);
					break;
				case "Long":
					returnMap.put(propertyName, 0l);
					break;
				case "BigDecimal":
					returnMap.put(propertyName, 0);
					break;
				case "int":
					returnMap.put(propertyName, 0);
					break;
				case "float":
					returnMap.put(propertyName, 0f);
					break;
				case "double":
					returnMap.put(propertyName, 0d);
					break;
				default:
					returnMap.put(propertyName, null);
				}

			}
		}
	}
	return returnMap;
}
 
Example 20
protected Map<String, Object> resolveBeanMetadata(final Object bean) {

        final Map<String, Object> beanMetadata = new LinkedHashMap<>();

        try {

            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {

                Method readMethod = propertyDescriptor.getReadMethod();

                if (readMethod != null && isSimpleType(propertyDescriptor.getPropertyType())) {

                    String name = Introspector.decapitalize(propertyDescriptor.getName());
                    Object value = readMethod.invoke(bean);

                    beanMetadata.put(name, value);
                }

            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return beanMetadata;

    }