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

The following examples show how to use java.beans.PropertyDescriptor#getWriteMethod() . 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 File: BeanConfigurator.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public static void loadBean(HierarchicalConfiguration context, Object beanObject, ConvertUtilsBean converter)   
{
	PropertyUtilsBean beanUtils = new PropertyUtilsBean(); 
	
	PropertyDescriptor[] descriptors = beanUtils.getPropertyDescriptors(beanObject);

	try
	{
		for ( PropertyDescriptor descr : descriptors )
		{
			//check that setter exists
			if ( descr.getWriteMethod() != null )
			{
				String value = context.getString(descr.getName());

                   if(converter.lookup(descr.getPropertyType()) != null) {
                       BeanUtils.setProperty(beanObject, descr.getName(), converter.convert(value, descr.getPropertyType()));
                   }
			}
		}
	}
	catch ( Exception e )
	{
		throw new EPSCommonException(e);
	}
}
 
Example 2
Source File: BeanUtil.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
/**
 * 将对象中的属性按属性名/属性值的方式存入到Map中。
 * 
 * @param bean
 * @param map
 * @param ignore
 */
public static void addBeanProperties2Map(Object bean, Map<String, Object> map, String...ignore){
    List<String> list = Arrays.asList(ignore);
    PropertyDescriptor[] descr = PropertyUtils.getPropertyDescriptors(bean);
    for (int i = 0; i < descr.length; i++) {
        PropertyDescriptor d = descr[i];
        String propertyName = d.getName();
        
        // 既有get又有set方法的属性的值才被读取 
        if ( d.getWriteMethod() == null || d.getReadMethod() == null) continue;
        
        if (list.contains(propertyName)) continue;
        
        try { // put value into Map
            map.put(propertyName, PropertyUtils.getProperty(bean, propertyName));
        } catch (Exception e) {
            log.info("获取属性名为:" + propertyName + " 的值时出错", e);
        }
    }
}
 
Example 3
Source File: Test4508780.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    for (String name : this.names) {
        Object bean;
        try {
            bean = this.loader.loadClass(name).newInstance();
        } catch (Exception exception) {
            throw new Error("could not instantiate bean: " + name, exception);
        }
        if (this.loader != bean.getClass().getClassLoader()) {
            throw new Error("bean class loader is not equal to default one");
        }
        PropertyDescriptor[] pds = getPropertyDescriptors(bean);
        for (PropertyDescriptor pd : pds) {
            Class type = pd.getPropertyType();
            Method setter = pd.getWriteMethod();
            Method getter = pd.getReadMethod();

            if (type.equals(String.class)) {
                executeMethod(setter, bean, "Foo");
            } else if (type.equals(int.class)) {
                executeMethod(setter, bean, Integer.valueOf(1));
            }
            executeMethod(getter, bean);
        }
    }
}
 
Example 4
Source File: BeanPropertyRowMapper.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Initialize the mapping meta-data for the given class.
 * @param mappedClass the mapped class
 */
protected void initialize(Class<T> mappedClass) {
	this.mappedClass = mappedClass;
	this.mappedFields = new HashMap<>();
	this.mappedProperties = new HashSet<>();
	PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
	for (PropertyDescriptor pd : pds) {
		if (pd.getWriteMethod() != null) {
			this.mappedFields.put(lowerCaseName(pd.getName()), pd);
			String underscoredName = underscoreName(pd.getName());
			if (!lowerCaseName(pd.getName()).equals(underscoredName)) {
				this.mappedFields.put(underscoredName, pd);
			}
			this.mappedProperties.add(pd.getName());
		}
	}
}
 
Example 5
Source File: ObjectMapperFactory.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isGetterVisible(Method m)
{
  if (m == null || !Modifier.isPublic(m.getModifiers())) {
    return false;
  }
  try {
    PropertyDescriptor[] pds = Introspector.getBeanInfo(m.getDeclaringClass()).getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
      if (pd.getReadMethod() != null && pd.getReadMethod().equals(m)) {
        Method setter = pd.getWriteMethod();
        if (setter == null || !Modifier.isPublic(setter.getModifiers())) {
          return false;
        } else {
          return true;
        }
      }
    }
  } catch (IntrospectionException e) {
    return false;
  }
  return false;
}
 
Example 6
Source File: Test4619536.java    From jdk8u-jdk with 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 7
Source File: Test4619536.java    From openjdk-8 with 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 File: BeanMap.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
private void initialise() {
    if(getBean() == null) return;

    Class  beanClass = getBean().getClass();
    try {
        //BeanInfo beanInfo = Introspector.getBeanInfo( bean, null );
        BeanInfo beanInfo = Introspector.getBeanInfo( beanClass );
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        if ( propertyDescriptors != null ) {
            for ( int i = 0; i < propertyDescriptors.length; i++ ) {
                PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
                if ( propertyDescriptor != null ) {
                    String name = propertyDescriptor.getName();
                    Method readMethod = propertyDescriptor.getReadMethod();
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    Class aType = propertyDescriptor.getPropertyType();

                    if ( readMethod != null ) {
                        readMethods.put( name, readMethod );
                    }
                    if ( writeMethods != null ) {
                        writeMethods.put( name, writeMethod );
                    }
                    types.put( name, aType );
                }
            }
        }
    }
    catch ( IntrospectionException e ) {
        logWarn(  e );
    }
}
 
Example 9
Source File: Test4168833.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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 File: PipelineOptionsFactory.java    From beam with Apache License 2.0 5 votes vote down vote up
/** Validates that setters don't have the given annotation. */
private static void validateSettersDoNotHaveAnnotation(
    SortedSetMultimap<Method, Method> methodNameToAllMethodMap,
    List<PropertyDescriptor> descriptors,
    AnnotationPredicates annotationPredicates) {
  List<AnnotatedSetter> annotatedSetters = new ArrayList<>();
  for (PropertyDescriptor descriptor : descriptors) {
    if (descriptor.getWriteMethod() == null
        || IGNORED_METHODS.contains(descriptor.getWriteMethod())) {
      continue;
    }
    SortedSet<Method> settersWithTheAnnotation =
        Sets.filter(
            methodNameToAllMethodMap.get(descriptor.getWriteMethod()),
            annotationPredicates.forMethod);

    Iterable<String> settersWithTheAnnotationClassNames =
        FluentIterable.from(settersWithTheAnnotation)
            .transform(MethodToDeclaringClassFunction.INSTANCE)
            .transform(ReflectHelpers.CLASS_NAME);

    if (!settersWithTheAnnotation.isEmpty()) {
      AnnotatedSetter annotated = new AnnotatedSetter();
      annotated.descriptor = descriptor;
      annotated.settersWithTheAnnotationClassNames = settersWithTheAnnotationClassNames;
      annotatedSetters.add(annotated);
    }
  }
  throwForSettersWithTheAnnotation(annotatedSetters, annotationPredicates.annotationClass);
}
 
Example 11
Source File: ApplicationContext.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public boolean isWritableProperty(String propertyName){
    PropertyDescriptor descriptor = getPropertyDescriptor(propertyName);
    if(descriptor == null){
        return false;
    }
    return descriptor.getWriteMethod() != null;
}
 
Example 12
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return an array of non-simple bean properties that are unsatisfied.
 * These are probably unsatisfied references to other beans in the
 * factory. Does not include simple properties like primitives or Strings.
 * @param mbd the merged bean definition the bean was created with
 * @param bw the BeanWrapper the bean was created with
 * @return an array of bean property names
 * @see org.springframework.beans.BeanUtils#isSimpleProperty
 */
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
	Set<String> result = new TreeSet<>();
	PropertyValues pvs = mbd.getPropertyValues();
	PropertyDescriptor[] pds = bw.getPropertyDescriptors();
	for (PropertyDescriptor pd : pds) {
		if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
				!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
			result.add(pd.getName());
		}
	}
	return StringUtils.toStringArray(result);
}
 
Example 13
Source File: PropertyDictionary.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Locates a serializable property.
 * 
 * @param cls
 * @param name
 * @deprecated As of 1.3.1, use {@link #propertyDescriptor(Class, String)} instead
 */
public BeanProperty property(Class cls, String name) {
    BeanProperty beanProperty = null;
    PropertyDescriptor descriptor = propertyDescriptorOrNull(cls, name);
    if (descriptor == null) {
        throw new MissingFieldException(cls.getName(), name);
    }
    if (descriptor.getReadMethod() != null && descriptor.getWriteMethod() != null) {
        beanProperty = new BeanProperty(
            cls, descriptor.getName(), descriptor.getPropertyType());
    }
    return beanProperty;
}
 
Example 14
Source File: Test4619536.java    From TencentKona-8 with 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 15
Source File: XxlConfFactory.java    From xxl-conf with GNU General Public License v3.0 4 votes vote down vote up
/**
 * refresh bean with xxl conf (fieldNames)
 */
public static void refreshBeanField(final BeanRefreshXxlConfListener.BeanField beanField, final String value, Object bean){
	if (bean == null) {
		bean = XxlConfFactory.beanFactory.getBean(beanField.getBeanName());		// 已优化:启动时禁止实用,getBean 会导致Bean提前初始化,风险较大;
	}
	if (bean == null) {
		return;
	}

	BeanWrapper beanWrapper = new BeanWrapperImpl(bean);

	// property descriptor
	PropertyDescriptor propertyDescriptor = null;
	PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
	if (propertyDescriptors!=null && propertyDescriptors.length>0) {
		for (PropertyDescriptor item: propertyDescriptors) {
			if (beanField.getProperty().equals(item.getName())) {
				propertyDescriptor = item;
			}
		}
	}

	// refresh field: set or field
	if (propertyDescriptor!=null && propertyDescriptor.getWriteMethod() != null) {
		beanWrapper.setPropertyValue(beanField.getProperty(), value);	// support mult data types
		logger.info(">>>>>>>>>>> xxl-conf, refreshBeanField[set] success, {}#{}:{}",
				beanField.getBeanName(), beanField.getProperty(), value);
	} else {

		final Object finalBean = bean;
		ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
			@Override
			public void doWith(Field fieldItem) throws IllegalArgumentException, IllegalAccessException {
				if (beanField.getProperty().equals(fieldItem.getName())) {
					try {
						Object valueObj = FieldReflectionUtil.parseValue(fieldItem.getType(), value);

						fieldItem.setAccessible(true);
						fieldItem.set(finalBean, valueObj);		// support mult data types

						logger.info(">>>>>>>>>>> xxl-conf, refreshBeanField[field] success, {}#{}:{}",
								beanField.getBeanName(), beanField.getProperty(), value);
					} catch (IllegalAccessException e) {
						throw new XxlConfException(e);
					}
				}
			}
		});

		/*Field[] beanFields = bean.getClass().getDeclaredFields();
		if (beanFields!=null && beanFields.length>0) {
			for (Field fieldItem: beanFields) {
				if (beanField.getProperty().equals(fieldItem.getName())) {
					try {
						Object valueObj = FieldReflectionUtil.parseValue(fieldItem.getType(), value);

						fieldItem.setAccessible(true);
						fieldItem.set(bean, valueObj);		// support mult data types

						logger.info(">>>>>>>>>>> xxl-conf, refreshBeanField[field] success, {}#{}:{}",
								beanField.getBeanName(), beanField.getProperty(), value);
					} catch (IllegalAccessException e) {
						throw new XxlConfException(e);
					}
				}
			}
		}*/
	}

}
 
Example 16
Source File: DefaultNodeDeserialiser.java    From workcraft with MIT License 4 votes vote down vote up
private boolean needDeserialisation(PropertyDescriptor desc) {
    return (desc.getPropertyType() != null) && (desc.getWriteMethod() != null) && (desc.getReadMethod() != null)
            && (desc.getReadMethod().getAnnotation(NoAutoSerialisation.class) == null)
            && (desc.getWriteMethod().getAnnotation(NoAutoSerialisation.class) == null);
}
 
Example 17
Source File: SpringSwaggerExtension.java    From swagger-maven-plugin with Apache License 2.0 4 votes vote down vote up
private List<Parameter> extractParametersFromModelAttributeAnnotation(Type type, Map<Class<?>, Annotation> annotations) {
    ModelAttribute modelAttribute = (ModelAttribute)annotations.get(ModelAttribute.class);
    if ((modelAttribute == null || !hasClassStartingWith(annotations.keySet(), "org.springframework.web.bind.annotation"))&& BeanUtils.isSimpleProperty(TypeUtils.getRawType(type, null))) {
        return Collections.emptyList();
    }

    List<Parameter> parameters = new ArrayList<Parameter>();
    Class<?> clazz = TypeUtils.getRawType(type, type);
    for (PropertyDescriptor propertyDescriptor : BeanUtils.getPropertyDescriptors(clazz)) {
        // Get all the valid setter methods inside the bean
        Method propertyDescriptorSetter = propertyDescriptor.getWriteMethod();
        if (propertyDescriptorSetter != null) {
            ApiParam propertySetterApiParam = AnnotationUtils.findAnnotation(propertyDescriptorSetter, ApiParam.class);
            if (propertySetterApiParam == null) {
                // If we find a setter that doesn't have @ApiParam annotation, then skip it
                continue;
            }

            // Here we have a bean setter method that is annotted with @ApiParam, but we still
            // need to know what type of parameter to create. In order to do this, we look for
            // any annotation attached to the first method parameter of the setter fucntion.
            Annotation[][] parameterAnnotations = propertyDescriptorSetter.getParameterAnnotations();
            if (parameterAnnotations == null || parameterAnnotations.length == 0) {
                continue;
            }

            Class parameterClass = propertyDescriptor.getPropertyType();
            List<Parameter> propertySetterExtractedParameters = this.extractParametersFromAnnotation(
                    parameterClass, toMap(Arrays.asList(parameterAnnotations[0])));

            for (Parameter parameter : propertySetterExtractedParameters) {
                if (Strings.isNullOrEmpty(parameter.getName())) {
                    parameter.setName(propertyDescriptor.getDisplayName());
                }
                ParameterProcessor.applyAnnotations(new Swagger(), parameter, type, Lists.newArrayList(propertySetterApiParam));
            }
            parameters.addAll(propertySetterExtractedParameters);
        }
    }

    return parameters;
}
 
Example 18
Source File: CmisTypeDefinitionFactoryBean.java    From spring-content with Apache License 2.0 4 votes vote down vote up
Updatability updatability(Class<?> clazz, Field field) {

		PropertyDescriptor descriptor = org.springframework.beans.BeanUtils.getPropertyDescriptor(clazz, field.getName());
		return (descriptor.getWriteMethod() != null) ? Updatability.READWRITE : Updatability.READONLY;
	}
 
Example 19
Source File: BeanInfoFinder.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@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 20
Source File: ReflectUtil.java    From blade-tool with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * 获取 类属性信息
 * @param propertyType 类型
 * @param propertyDescriptor PropertyDescriptor
 * @param propertyName 属性名
 * @return {Property}
 */
public static TypeDescriptor getTypeDescriptor(Class<?> propertyType, PropertyDescriptor propertyDescriptor, String propertyName) {
	Method readMethod = propertyDescriptor.getReadMethod();
	Method writeMethod = propertyDescriptor.getWriteMethod();
	Property property = new Property(propertyType, readMethod, writeMethod, propertyName);
	return new TypeDescriptor(property);
}