Java Code Examples for java.beans.PropertyDescriptor

The following examples show how to use java.beans.PropertyDescriptor. 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
/**
  * Gets the Property Descriptors
  *
  * @return   The propertyDescriptors value
  */
 public PropertyDescriptor[] getPropertyDescriptors() 
 {
    try
    {
       Vector descriptors = new Vector();
       PropertyDescriptor descriptor = null;

       return (PropertyDescriptor[]) descriptors.toArray(new PropertyDescriptor[descriptors.size()]);
    }
    catch (Exception e)
    {
       // do not ignore, bomb politely so use has chance to discover what went wrong...
// I know that this is suboptimal solution, but swallowing silently is
// even worse... Propose better solution! 
e.printStackTrace();
    }
    return null;
 }
 
Example 2
Source Project: j2objc   Source File: IntrospectorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_MixedBooleanSimpleClass11() throws Exception {
    BeanInfo info = Introspector
            .getBeanInfo(MixedBooleanSimpleClass11.class);
    Method setter = MixedBooleanSimpleClass11.class.getDeclaredMethod(
            "setList", int.class, boolean.class);

    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        if (propertyName.equals(pd.getName())) {
            assertTrue(pd instanceof IndexedPropertyDescriptor);
            assertNull(pd.getReadMethod());
            assertNull(pd.getWriteMethod());
            assertNull(((IndexedPropertyDescriptor) pd)
                    .getIndexedReadMethod());
            assertEquals(setter, ((IndexedPropertyDescriptor) pd)
                    .getIndexedWriteMethod());
        }
    }
}
 
Example 3
Source Project: mPaaS   Source File: ReflectUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取bean的字段值
 */
@SuppressWarnings("unchecked")
public static <T> T getProperty(Object bean, String prop)
        throws ReflectiveOperationException {
    if (bean == null) {
        return null;
    }
    if (bean instanceof Map<?, ?>) {
        return (T) ((Map<?, ?>) bean).get(prop);
    }
    PropertyDescriptor desc = BeanUtils
            .getPropertyDescriptor(bean.getClass(), prop);
    if (desc == null) {
        throw new NoSuchFieldException();
    }
    Method method = desc.getReadMethod();
    if (method == null) {
        throw new NoSuchMethodException();
    }
    return (T) method.invoke(bean);
}
 
Example 4
Source Project: jdk8u60   Source File: Test4634390.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void test(Class type) {
    for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(type)) {
        PropertyDescriptor pdCopy = create(pd);
        if (pdCopy != null) {
            // XXX - hack! The Introspector will set the bound property
            // since it assumes that propertyChange event set descriptors
            // infers that all the properties are bound
            pdCopy.setBound(pd.isBound());

            String name = pd.getName();
            System.out.println(" - " + name);

            if (!compare(pd, pdCopy))
                throw new Error("property delegates are not equal");

            if (!pd.equals(pdCopy))
                throw new Error("equals() failed");

            if (pd.hashCode() != pdCopy.hashCode())
                throw new Error("hashCode() failed");
        }
    }
}
 
Example 5
Source Project: jdk8u-jdk   Source File: Test7192955.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "test").isBound()) {
        throw new Error("a simple property is not bound");
    }
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "list").isBound()) {
        throw new Error("a generic property is not bound");
    }
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "readOnly").isBound()) {
        throw new Error("a read-only property is not bound");
    }
    PropertyDescriptor[] pds = Introspector.getBeanInfo(MyBean.class, BaseBean.class).getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        if (pd.getName().equals("test") && pd.isBound()) {
            throw new Error("a simple property is bound without superclass");
        }
    }
}
 
Example 6
Source Project: commons-configuration   Source File: BeanHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the Class of the property if it can be determined.
 * @param bean The bean containing the property.
 * @param propName The name of the property.
 * @return The class associated with the property or null.
 */
private static Class<?> getDefaultClass(final Object bean, final String propName)
{
    try
    {
        final PropertyDescriptor desc =
                BEAN_UTILS_BEAN.getPropertyUtils().getPropertyDescriptor(
                        bean, propName);
        if (desc == null)
        {
            return null;
        }
        return desc.getPropertyType();
    }
    catch (final Exception ex)
    {
        return null;
    }
}
 
Example 7
Source Project: waterdrop   Source 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 8
Source Project: armeria   Source File: AbstractArmeriaBeanPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private LocalArmeriaPortElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
    super(member, pd);
    final LocalArmeriaPort localArmeriaPort = ae.getAnnotation(LocalArmeriaPort.class);
    final SessionProtocol protocol = localArmeriaPort.value();
    Server server = getServer();
    if (server == null) {
        server = beanFactory.getBean(Server.class);
        serServer(server);
    }

    Integer port = portCache.get(protocol);
    if (port == null) {
        port = server.activeLocalPort(protocol);
        portCache.put(protocol, port);
    }
    this.port = port;
}
 
Example 9
Source Project: commons-beanutils   Source File: PropertyUtilsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Positive test for getPropertyDescriptors().  Each property name
 * listed in {@code properties} should be returned exactly once.
 */
public void testGetDescriptors() {

    final PropertyDescriptor[] pd =
            PropertyUtils.getPropertyDescriptors(bean);
    assertNotNull("Got descriptors", pd);
    final int[] count = new int[properties.length];
    for (final PropertyDescriptor element : pd) {
        final String name = element.getName();
        for (int j = 0; j < properties.length; j++) {
            if (name.equals(properties[j])) {
                count[j]++;
            }
        }
    }
    for (int j = 0; j < properties.length; j++) {
        if (count[j] < 0) {
            fail("Missing property " + properties[j]);
        } else if (count[j] > 1) {
            fail("Duplicate property " + properties[j]);
        }
    }

}
 
Example 10
Source Project: jt808-server   Source File: MessageDecoder.java    License: Apache License 2.0 6 votes vote down vote up
public <T> T decode(ByteBuf buf, Class<T> targetClass) {
    T result = BeanUtils.newInstance(targetClass);

    PropertyDescriptor[] pds = getPropertyDescriptor(targetClass);
    for (PropertyDescriptor pd : pds) {

        Method readMethod = pd.getReadMethod();
        Property prop = readMethod.getDeclaredAnnotation(Property.class);
        int length = getLength(result, prop);
        if (!buf.isReadable(length))
            break;

        if (length == -1)
            length = buf.readableBytes();
        Object value = null;
        try {
            value = read(buf, prop, length, pd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        BeanUtils.setValue(result, pd.getWriteMethod(), value);
    }
    return result;
}
 
Example 11
/**
 * Sets properties from the BeanInfo supplement on the
 * introspected PropertyDescriptor
 */
private void setDocInfoProps(DocBeanInfo dbi, PropertyDescriptor pds) {
    int beanflags = dbi.beanflags;

    if ((beanflags & DocBeanInfo.BOUND) != 0)
        pds.setBound(true);
    if ((beanflags & DocBeanInfo.EXPERT) != 0)
        pds.setExpert(true);
    if ((beanflags & DocBeanInfo.CONSTRAINED) != 0)
        pds.setConstrained(true);
    if ((beanflags & DocBeanInfo.HIDDEN) !=0)
        pds.setHidden(true);
    if ((beanflags & DocBeanInfo.PREFERRED) !=0)
        pds.setPreferred(true);

    if (!(dbi.desc.equals("null"))){
        pds.setShortDescription(dbi.desc);
    }
    if (!(dbi.displayname.equals("null"))){
        pds.setDisplayName(dbi.displayname);
    }
}
 
Example 12
Source Project: jdk8u-jdk   Source File: Test4634390.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static PropertyDescriptor create(PropertyDescriptor pd) {
    try {
        if (pd instanceof IndexedPropertyDescriptor) {
            IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
            return new IndexedPropertyDescriptor(
                    ipd.getName(),
                    ipd.getReadMethod(),
                    ipd.getWriteMethod(),
                    ipd.getIndexedReadMethod(),
                    ipd.getIndexedWriteMethod());
        } else {
            return new PropertyDescriptor(
                    pd.getName(),
                    pd.getReadMethod(),
                    pd.getWriteMethod());
        }
    }
    catch (IntrospectionException exception) {
        exception.printStackTrace();
        return null;
    }
}
 
Example 13
Source Project: j2objc   Source File: IntrospectorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_MixedSimpleClass30() throws Exception {
    BeanInfo info = Introspector.getBeanInfo(MixedSimpleClass30.class);
    Method indexedGetter = MixedSimpleClass30.class.getDeclaredMethod(
            "getList", int.class);

    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        if (propertyName.equals(pd.getName())) {
            assertTrue(pd instanceof IndexedPropertyDescriptor);
            assertNull(pd.getReadMethod());
            assertNull(pd.getWriteMethod());
            assertEquals(indexedGetter, ((IndexedPropertyDescriptor) pd)
                    .getIndexedReadMethod());
            assertNull(((IndexedPropertyDescriptor) pd)
                    .getIndexedWriteMethod());

        }
    }
}
 
Example 14
Source Project: SpringBoot2.0   Source File: BeanUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> transBeanToMap(Object obj) {
    if (obj == null) {
        return null;
    }
    Map<String, Object> map = new HashMap<>();
    try {
        PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(obj);
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (!key.equals("class")) {
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}
 
Example 15
Source Project: onetwo   Source File: CommonPropertyValueSetter.java    License: Apache License 2.0 6 votes vote down vote up
protected void copyArray(SimpleBeanCopier beanCopier, BeanWrapper targetBeanWrapper, Class<?> propertyType, Cloneable cloneable, PropertyDescriptor toProperty, Object srcValue){
		Assert.isTrue(propertyType==srcValue.getClass(), "property type is not equals srcValue type");
		int length = Array.getLength(srcValue);
		Object array = Array.newInstance(propertyType.getComponentType(), length);
		
		if(isContainerValueCopyValueOrRef(cloneable, srcValue)){
			for (int i = 0; i < length; i++) {
				Array.set(array, i, Array.get(srcValue, i));
			}
		}else{
			for (int i = 0; i < length; i++) {
//				Object targetElement = newBeanCopier(propertyType.getComponentType()).fromObject(Array.get(array, i));
				Object targetElement = beanCopier.fromObject(Array.get(array, i), propertyType.getComponentType());
				Array.set(array, i, targetElement);
			}
		}
//		targetBeanWrapper.setPropertyValue(toProperty.getName(), array);
		setPropertyValue0(targetBeanWrapper, toProperty.getName(), array);
	}
 
Example 16
Source Project: danyuan-application   Source File: BeanUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void transMap2Bean(Map<String, Object> map, Object obj) {

		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();

				if (map.containsKey(key)) {
					Object value = map.get(key);
					// 得到property对应的setter方法
					Method setter = property.getWriteMethod();
					setter.invoke(obj, value);
				}

			}

		} catch (Exception e) {
			System.out.println("transMap2Bean Error " + e);
		}

		return;

	}
 
Example 17
/**
 * Utility method which can take one payment and distribute its amount by ratio to the target payments
 * 
 * @param source Source Payment
 * @param targets Target Payment
 * @param ratios Ratio to be applied for each target
 */
private void applyRatioToPaymentAmounts(AssetPayment source, AssetPayment[] targets, double[] ratios) {
    try {
        for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                KualiDecimal amount = (KualiDecimal) readMethod.invoke(source);
                if (amount != null && amount.isNonZero()) {
                    KualiDecimal[] ratioAmounts = KualiDecimalUtils.allocateByRatio(amount, ratios);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    if (writeMethod != null) {
                        for (int i = 0; i < ratioAmounts.length; i++) {
                            writeMethod.invoke(targets[i], ratioAmounts[i]);
                        }
                    }
                }
            }
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 18
Source Project: j2objc   Source File: IntrospectorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_MixedBooleanExtendClass12() throws Exception {
    BeanInfo info = Introspector
            .getBeanInfo(MixedBooleanExtendClass12.class);
    Method getter = MixedBooleanSimpleClass41.class
            .getDeclaredMethod("getList");
    Method setter = MixedBooleanSimpleClass41.class.getDeclaredMethod(
            "setList", boolean.class);

    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        if (propertyName.equals(pd.getName())) {
            assertFalse(pd instanceof IndexedPropertyDescriptor);
            assertEquals(getter, pd.getReadMethod());
            assertEquals(setter, pd.getWriteMethod());
        }
    }
}
 
Example 19
/**
 * Creates a description for the attribute corresponding to this property
 * descriptor. Attempts to create the description using metadata from either
 * the getter or setter attributes, otherwise uses the property name.
 */
@Override
protected String getAttributeDescription(PropertyDescriptor propertyDescriptor, String beanKey) {
	Method readMethod = propertyDescriptor.getReadMethod();
	Method writeMethod = propertyDescriptor.getWriteMethod();

	ManagedAttribute getter =
			(readMethod != null ? this.attributeSource.getManagedAttribute(readMethod) : null);
	ManagedAttribute setter =
			(writeMethod != null ? this.attributeSource.getManagedAttribute(writeMethod) : null);

	if (getter != null && StringUtils.hasText(getter.getDescription())) {
		return getter.getDescription();
	}
	else if (setter != null && StringUtils.hasText(setter.getDescription())) {
		return setter.getDescription();
	}

	ManagedMetric metric = (readMethod != null ? this.attributeSource.getManagedMetric(readMethod) : null);
	if (metric != null && StringUtils.hasText(metric.getDescription())) {
		return metric.getDescription();
	}

	return propertyDescriptor.getDisplayName();
}
 
Example 20
Source Project: tutorials   Source File: BaeldungReflectionUtils.java    License: MIT License 5 votes vote down vote up
static List<String> getNullPropertiesList(Customer customer) throws Exception {
    PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();

    return Arrays.stream(propDescArr)
      .filter(nulls(customer))
      .map(PropertyDescriptor::getName)
      .collect(Collectors.toList());
}
 
Example 21
Source Project: feilong-core   Source File: GetValueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = NullPointerException.class)
//@Test
public void testGetValueError() throws IntrospectionException{
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(StoreLocatorErrorProperty.class);

    //---------------------------------------------------------------
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors){

        PropertyValueObtainer.getValue(new StoreLocatorErrorProperty(), propertyDescriptor);
    }

}
 
Example 22
Source Project: jdk8u60   Source File: Test7122740.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    long time = System.nanoTime();
    for (int i = 0; i < 1000; i++) {
        new PropertyDescriptor("name", PropertyDescriptor.class);
        new PropertyDescriptor("value", Concrete.class);
    }
    time -= System.nanoTime();
    System.out.println("Time (ms): " + (-time / 1000000));
}
 
Example 23
Source Project: jeecg   Source File: MigrateForm.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlParameterSource generateParameterMap(Object t, List<String> ignores){
	Map<String, Object> paramMap = new HashMap<String, Object>();
	ReflectHelper reflectHelper = new ReflectHelper(t);
	PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(t.getClass());
	for (PropertyDescriptor pd : pds) {
		if(null != ignores && ignores.contains(pd.getName())){
			continue;
		}
		paramMap.put(pd.getName(), reflectHelper.getMethodValue(pd.getName()));
	}
	MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(paramMap);
	return sqlParameterSource;
}
 
Example 24
public static void main(String[] args) {
    PropertyDescriptor[] array = BeanUtils.getPropertyDescriptors(SimpleBean.class);
    for (PropertyDescriptor pd : array) {
        BeanUtils.reportPropertyDescriptor(pd);
    }
    if (array.length != 3)
        throw new Error("unexpected count of properties: " + array.length);
}
 
Example 25
Source Project: jdk8u-dev-jdk   Source File: Test4168833.java    License: 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 26
Source Project: TencentKona-8   Source File: BeanUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an array of property descriptors for specified class.
 *
 * @param type  the class to introspect
 * @return an array of property descriptors
 */
public static PropertyDescriptor[] getPropertyDescriptors(Class type) {
    try {
        return Introspector.getBeanInfo(type).getPropertyDescriptors();
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
}
 
Example 27
Source Project: hypergraphdb   Source File: BonesOfBeans.java    License: Apache License 2.0 5 votes vote down vote up
private static Map<String, PropertyDescriptor> getpropmap(Class<?> clazz,
		boolean incl_cls)
{
	HashMap<String, PropertyDescriptor> propmap = null; // cache.get(clazz);
	if (propmap == null)
	{
		try
		{
			BeanInfo bean_info = Introspector.getBeanInfo(clazz);
			propmap = new HashMap<String, PropertyDescriptor>();
			PropertyDescriptor beanprops[] = bean_info
					.getPropertyDescriptors();
			for (int i = 0; i < beanprops.length; i++)
			{
				// filter the Class property which is not used
				if (!incl_cls && "class".equals(beanprops[i].getName()))
					continue;
				propmap.put(beanprops[i].getName(), beanprops[i]);
			}
			// cache.put(clazz, propmap);
		} catch (IntrospectionException ex)
		{
			throw new HGException("The bean " + clazz.getName()
					+ " doesn't want us to introspect it: " + ex.toString());
		}
	}
	return propmap;
}
 
Example 28
Source Project: stategen   Source File: BeanHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static void copyProperties(Object target, Map source,boolean ignoreCase)  {
    Set<String> keys = source.keySet();
    for(String key : keys) {
        if ("xml:base".equalsIgnoreCase(key)){
            continue;
        }
    	PropertyDescriptor pd = getPropertyDescriptor(target.getClass(), key, ignoreCase);
    	if(pd == null) {
    		throw new IllegalArgumentException("not found property:'"+key+"' on class:"+target.getClass());
    	}
    	setProperty(target, pd, source.get(key));
    }
}
 
Example 29
Source Project: ion-java   Source File: Injected.java    License: Apache License 2.0 5 votes vote down vote up
private static Dimension[] findDimensions(TestClass testClass)
throws Throwable
{
    List<FrameworkField> fields =
        testClass.getAnnotatedFields(Inject.class);
    if (fields.isEmpty())
    {
        throw new Exception("No fields of " + testClass.getName()
                            + " have the @Inject annotation");
    }

    BeanInfo beanInfo = Introspector.getBeanInfo(testClass.getJavaClass());
    PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();

    Dimension[] dimensions = new Dimension[fields.size()];

    int i = 0;
    for (FrameworkField field : fields)
    {
        int modifiers = field.getField().getModifiers();
        if (! Modifier.isPublic(modifiers) || ! Modifier.isStatic(modifiers))
        {
            throw new Exception("@Inject " + testClass.getName() + '.'
                                + field.getField().getName()
                                + " must be public static");
        }

        Dimension dim = new Dimension();
        dim.property = field.getField().getAnnotation(Inject.class).value();
        dim.descriptor = findDescriptor(testClass, descriptors, field, dim.property);
        dim.values = (Object[]) field.get(null);
        dimensions[i++] = dim;
    }

    return dimensions;
}
 
Example 30
Source Project: hottub   Source File: Test4168833.java    License: 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");
    }
}