java.beans.Introspector Java Examples

The following examples show how to use java.beans.Introspector. 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: TypeReflector.java    From ask-sdk-frameworks-java with Apache License 2.0 6 votes vote down vote up
public TypeReflector(JavaType javaType) {
    this.javaType = assertNotNull(javaType, "javaType");
    try {
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(javaType.getRawClass()).getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) {
                continue; // TODO: Warn? Error?
            }

            this.propertyDescriptors.add(descriptor);
            this.setters.put(descriptor.getName(), makeSetter(descriptor));
            this.getters.put(descriptor.getName(), makeGetter(descriptor));
        }
    } catch (IntrospectionException ex) {
        throw new IllegalArgumentException("Could not introspect bean: " + javaType.getTypeName(), ex);
    }

    this.propertyDescriptorIndex = propertyDescriptors.stream().collect(Collectors.toMap(
        PropertyDescriptor::getName,
        p -> p
    ));
}
 
Example #2
Source File: ApplicationX.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
private static PropertyDescriptor[] getPropertyDescriptorsIfCache(Class clazz) throws IllegalStateException{
    PropertyDescriptor[] result = PROPERTY_DESCRIPTOR_CACHE_MAP.get(clazz);
    if(result == null) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class, Introspector.USE_ALL_BEANINFO);
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            if(descriptors != null){
                result = descriptors;
            }else {
                result = EMPTY_DESCRIPTOR_ARRAY;
            }
            PROPERTY_DESCRIPTOR_CACHE_MAP.put(clazz,result);
        } catch (IntrospectionException e) {
            throw new IllegalStateException("getPropertyDescriptors error. class=" + clazz+e,e);
        }
        // TODO: 1月28日 028 getPropertyDescriptorsIfCache
        // skip GenericTypeAwarePropertyDescriptor leniently resolves a set* write method
        // against a declared read method, so we prefer read method descriptors here.
    }
    return result;
}
 
Example #3
Source File: DtoUtils.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> toMap(Object bean) {

        if (bean == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性,否则输出结果会有 class 属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(bean);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return map;
    }
 
Example #4
Source File: Test4508780.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static PropertyDescriptor[] getPropertyDescriptors(Object object) {
    Class type = object.getClass();
    synchronized (System.out) {
        System.out.println(type);
        ClassLoader loader = type.getClassLoader();
        while (loader != null) {
            System.out.println(" - loader: " + loader);
            loader = loader.getParent();
        }
    }
    try {
        return Introspector.getBeanInfo(type).getPropertyDescriptors();
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
}
 
Example #5
Source File: Test6447751.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void test(Class<?> type, Class<?> expected) {
    Class<?> actual;
    try {
        actual = Introspector.getBeanInfo(type).getBeanDescriptor().getCustomizerClass();
    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected error", exception);
    }
    if (actual != expected) {
        StringBuilder sb = new StringBuilder();
        sb.append("bean ").append(type).append(": ");
        if (expected != null) {
            sb.append("expected ").append(expected);
            if (actual != null) {
                sb.append(", but ");
            }
        }
        if (actual != null) {
            sb.append("found ").append(actual);
        }
        throw new Error(sb.toString());
    }
}
 
Example #6
Source File: AbstractParametrizedWidget.java    From bonita-ui-designer with GNU General Public License v2.0 6 votes vote down vote up
private Map<String, Object> toMap() {
    try {
        Map<String, Object> params = new HashMap<>();
        ArrayList<String> availableProperties = new ArrayList<>();
        availableProperties.addAll(classesIntrospection(this.getClass()));

        BeanInfo info = Introspector.getBeanInfo(this.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            Method reader = pd.getReadMethod();
            if (reader != null && availableProperties.contains(pd.getName())) {
                params.put(pd.getName(), reader.invoke(this));
            }
        }
        return params;
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        return Collections.emptyMap();
    }
}
 
Example #7
Source File: IntrospectorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testMockIncompatibleAllSetterAndGetterBean() throws Exception {
    Class<?> beanClass = MockIncompatibleAllSetterAndGetterBean.class;
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    PropertyDescriptor pd = null;
    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    for (int i = 0; i < pds.length; i++) {
        pd = pds[i];
        if (pd.getName().equals("data")) {
            break;
        }
    }
    assertNotNull(pd);
    assertTrue(pd instanceof IndexedPropertyDescriptor);
    IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
    assertNull(ipd.getReadMethod());
    assertNull(ipd.getWriteMethod());
    Method indexedReadMethod = beanClass.getMethod("getData",
            new Class[] { int.class });
    Method indexedWriteMethod = beanClass.getMethod("setData", new Class[] {
            int.class, int.class });
    assertEquals(indexedReadMethod, ipd.getIndexedReadMethod());
    assertEquals(indexedWriteMethod, ipd.getIndexedWriteMethod());
}
 
Example #8
Source File: Test7192955.java    From jdk8u-jdk with 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 #9
Source File: BeanUtils.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the properties from a Java Bean and returns them in a Map of String
 * name/value pairs. Because this method has to know how to convert a
 * bean property into a String value, only a few bean property
 * types are supported. They are: String, boolean, int, long, float, double,
 * Color, and Class.
 *
 * @param bean a Java Bean to get properties from.
 * @return a Map of all properties as String name/value pairs.
 */
public static Map<String, String> getProperties(Object bean) {
    Map<String, String> properties = new HashMap<>();
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        // Loop through all properties of the bean.
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        String [] names = new String[descriptors.length];
        for (int i=0; i<names.length; i++) {
            // Determine the property name.
            String name = descriptors[i].getName();
            //Class type = descriptors[i].getPropertyType();
            // Decode the property value using the property type and
            // encoded String value.
            Object value = descriptors[i].getReadMethod().invoke(bean,(java.lang.Object[]) null);
            // Add to Map, encoding the value as a String.
            properties.put(name, encode(value));
        }
    }
    catch (Exception e) {
        Log.error(e.getMessage(), e);
    }
    return properties;
}
 
Example #10
Source File: TmpPattern.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Based on names of getter and setter resolves the name of the property.
 * @return Name of the property
 */
String findPropertyName() {
    String methodName = null;

    if ( getterMethod != null )
        methodName = nameAsString(getterMethod);
    else if ( setterMethod != null )
        methodName = nameAsString(setterMethod);
    else {
        return null;
    }

    return  methodName.startsWith( IS_PREFIX ) ? // NOI18N
            Introspector.decapitalize( methodName.substring(2) ) :
            Introspector.decapitalize( methodName.substring(3) );
}
 
Example #11
Source File: Test4508780.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static PropertyDescriptor[] getPropertyDescriptors(Object object) {
    Class type = object.getClass();
    synchronized (System.out) {
        System.out.println(type);
        ClassLoader loader = type.getClassLoader();
        while (loader != null) {
            System.out.println(" - loader: " + loader);
            loader = loader.getParent();
        }
    }
    try {
        return Introspector.getBeanInfo(type).getPropertyDescriptors();
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
}
 
Example #12
Source File: ReflectionProtoGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public Collection<Class<?>> extractDataClasses(Collection<Class<?>> input, String targetDirectory) {

        Set<Class<?>> dataModelClasses = new HashSet<>();
        for (Class<?> modelClazz : input) {
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(modelClazz);
                for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                    Class<?> propertyType = pd.getPropertyType();
                    if (propertyType.getCanonicalName().startsWith("java.lang") 
                            || propertyType.getCanonicalName().equals(Date.class.getCanonicalName())) {
                        continue;
                    }

                    dataModelClasses.add(propertyType);
                }

                generateModelClassProto(modelClazz, targetDirectory);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return dataModelClasses;
    }
 
Example #13
Source File: TestIntrospector.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    StringBuilder sb = null;
    if (args.length > 0) {
        if (args[0].equals("show")) {
            sb = new StringBuilder(65536);
        }
    }
    Introspector.flushCaches();
    int count = (sb != null) ? 10 : 100;
    long time = -System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        test(sb);
        test(sb);
        Introspector.flushCaches();
    }
    time += System.currentTimeMillis();
    System.out.println("Time (average): " + time / count);
}
 
Example #14
Source File: TestIntrospector.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    StringBuilder sb = null;
    if (args.length > 0) {
        if (args[0].equals("show")) {
            sb = new StringBuilder(65536);
        }
    }
    Introspector.flushCaches();
    int count = (sb != null) ? 10 : 100;
    long time = -System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        test(sb);
        test(sb);
        Introspector.flushCaches();
    }
    time += System.currentTimeMillis();
    System.out.println("Time (average): " + time / count);
}
 
Example #15
Source File: Test6447751.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void test(Class<?> type, Class<?> expected) {
    Class<?> actual;
    try {
        actual = Introspector.getBeanInfo(type).getBeanDescriptor().getCustomizerClass();
    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected error", exception);
    }
    if (actual != expected) {
        StringBuilder sb = new StringBuilder();
        sb.append("bean ").append(type).append(": ");
        if (expected != null) {
            sb.append("expected ").append(expected);
            if (actual != null) {
                sb.append(", but ");
            }
        }
        if (actual != null) {
            sb.append("found ").append(actual);
        }
        throw new Error(sb.toString());
    }
}
 
Example #16
Source File: Test6447751.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void test(Class<?> type, Class<?> expected) {
    Class<?> actual;
    try {
        actual = Introspector.getBeanInfo(type).getBeanDescriptor().getCustomizerClass();
    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected error", exception);
    }
    if (actual != expected) {
        StringBuilder sb = new StringBuilder();
        sb.append("bean ").append(type).append(": ");
        if (expected != null) {
            sb.append("expected ").append(expected);
            if (actual != null) {
                sb.append(", but ");
            }
        }
        if (actual != null) {
            sb.append("found ").append(actual);
        }
        throw new Error(sb.toString());
    }
}
 
Example #17
Source File: DefaultToSoyDataConverter.java    From spring-soy-view with Apache License 2.0 6 votes vote down vote up
protected Map<String, ?> pojoToMap(final Object pojo) {
	Map<String, Object> map = new HashMap<String, Object>();

	try {
		final BeanInfo beanInfo = Introspector.getBeanInfo(pojo.getClass());

		PropertyDescriptor[] propertyDescriptors = beanInfo
				.getPropertyDescriptors();
		for (PropertyDescriptor pd : propertyDescriptors) {
			if (!isIgnorable(pd)) {
				map.put(pd.getName(), pd.getReadMethod().invoke(pojo));
			}
		}

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

	return map;
}
 
Example #18
Source File: Test7192955.java    From jdk8u_jdk with 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 #19
Source File: TestIntrospector.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    StringBuilder sb = null;
    if (args.length > 0) {
        if (args[0].equals("show")) {
            sb = new StringBuilder(65536);
        }
    }
    Introspector.flushCaches();
    int count = (sb != null) ? 10 : 100;
    long time = -System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        test(sb);
        test(sb);
        Introspector.flushCaches();
    }
    time += System.currentTimeMillis();
    System.out.println("Time (average): " + time / count);
}
 
Example #20
Source File: AbstractVisualResource.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Sets the value for a specified parameter.
 *
 * @param paramaterName the name for the parameteer
 * @param parameterValue the value the parameter will receive
 */
@Override
public void setParameterValue(String paramaterName, Object parameterValue)
            throws ResourceInstantiationException{
  // get the beaninfo for the resource bean, excluding data about Object
  BeanInfo resBeanInf = null;
  try {
    resBeanInf = Introspector.getBeanInfo(this.getClass(), Object.class);
  } catch(Exception e) {
    throw new ResourceInstantiationException(
      "Couldn't get bean info for resource " + this.getClass().getName()
      + Strings.getNl() + "Introspector exception was: " + e
    );
  }
  AbstractResource.setParameterValue(this, resBeanInf, paramaterName, parameterValue);
}
 
Example #21
Source File: ExtendedBeanInfoTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void nonPublicStandardReadAndWriteMethods() throws Exception {
	@SuppressWarnings("unused") class C {
		String getFoo() { return null; }
		C setFoo(String foo) { return this; }
	}

	BeanInfo bi = Introspector.getBeanInfo(C.class);
	BeanInfo ebi = new ExtendedBeanInfo(bi);

	assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
	assertThat(hasWriteMethodForProperty(bi, "foo"), is(false));

	assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
	assertThat(hasWriteMethodForProperty(ebi, "foo"), is(false));
}
 
Example #22
Source File: ExtendedBeanInfoTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void nonStandardReadMethodAndStandardWriteMethod() throws IntrospectionException {
	@SuppressWarnings("unused") class C {
		public void getFoo() { }
		public void setFoo(String foo) { }
	}

	BeanInfo bi = Introspector.getBeanInfo(C.class);
	BeanInfo ebi = new ExtendedBeanInfo(bi);

	assertThat(hasReadMethodForProperty(bi, "foo"), is(false));
	assertThat(hasWriteMethodForProperty(bi, "foo"), is(true));

	assertThat(hasReadMethodForProperty(ebi, "foo"), is(false));
	assertThat(hasWriteMethodForProperty(ebi, "foo"), is(true));
}
 
Example #23
Source File: Test6660539.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static PropertyDescriptor[] getPropertyDescriptors() {
    try {
        BeanInfo info = Introspector.getBeanInfo(Test6660539.class);
        return info.getPropertyDescriptors();
    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected", exception);
    }
}
 
Example #24
Source File: TestIntrospector.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void test(StringBuilder sb, Class type) throws IntrospectionException {
    long time = 0L;
    if (sb != null) {
        time = -System.currentTimeMillis();
    }
    BeanInfo info = Introspector.getBeanInfo(type);
    if (sb != null) {
        time += System.currentTimeMillis();
        sb.append('\n').append(time);
        sb.append('\t').append(info.getPropertyDescriptors().length);
        sb.append('\t').append(info.getEventSetDescriptors().length);
        sb.append('\t').append(info.getMethodDescriptors().length);
        sb.append('\t').append(type.getName());
    }
}
 
Example #25
Source File: IntrospectorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_MixedSimpleClass5() throws Exception {
    BeanInfo info = Introspector.getBeanInfo(MixedSimpleClass5.class);
    Method getter = MixedSimpleClass5.class.getDeclaredMethod("getList");
    Method setter = MixedSimpleClass5.class.getDeclaredMethod("setList",
            Object.class);

    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        if (propertyName.equals(pd.getName())) {
            assertFalse(pd instanceof IndexedPropertyDescriptor);
            assertEquals(getter, pd.getReadMethod());
            assertEquals(setter, pd.getWriteMethod());
        }
    }
}
 
Example #26
Source File: BeanUtils.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an array of event set descriptors for specified class.
 *
 * @param type  the class to introspect
 * @return an array of event set descriptors
 */
public static EventSetDescriptor[] getEventSetDescriptors(Class type) {
    try {
        return Introspector.getBeanInfo(type).getEventSetDescriptors();
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
}
 
Example #27
Source File: DataFileGeneratorTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void assertBeansEqual(String message,
                                Set<Object> comparedObjects,
                                Object expected,
                                Object actual) throws Exception {
   assertNotNull("Actual object should be equal to: " + expected + " but was null", actual);
   if (comparedObjects.contains(expected)) {
      return;
   }
   comparedObjects.add(expected);
   Class<? extends Object> type = expected.getClass();
   assertEquals("Should be of same type", type, actual.getClass());
   BeanInfo beanInfo = Introspector.getBeanInfo(type);
   PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
   for (int i = 0; i < descriptors.length; i++) {
      PropertyDescriptor descriptor = descriptors[i];
      Method method = descriptor.getReadMethod();
      if (method != null) {
         String name = descriptor.getName();
         Object expectedValue = null;
         Object actualValue = null;
         try {
            expectedValue = method.invoke(expected, EMPTY_ARGUMENTS);
            actualValue = method.invoke(actual, EMPTY_ARGUMENTS);
         } catch (Exception e) {
            LOG.info("Failed to access property: " + name);
         }
         assertPropertyValuesEqual(message + name, comparedObjects, expectedValue, actualValue);
      }
   }
}
 
Example #28
Source File: BeanUtils.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> transBean2Map(Object obj) {

		if (obj == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			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) {
			System.out.println("transBean2Map Error " + e);
		}

		return map;

	}
 
Example #29
Source File: ClassUtils.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static String getFieldNameFromGetter(Method getter) {
    String name = getter.getName();
    if (name.startsWith("get") && name.length() > 3 && Character.isUpperCase(name.charAt(3))) {
        name = getter.getName().replaceAll("^get", "");
    } else if (name.startsWith("is") && name.length() > 2 && Character.isUpperCase(name.charAt(2))) {
        name = getter.getName().replaceAll("^is", "");
    }
    return Introspector.decapitalize(name);
}
 
Example #30
Source File: Test4144543.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Class type = Beans.instantiate(null, "Test4144543").getClass();

    // try all the various places that this would break before

    Introspector.getBeanInfo(type);
    new PropertyDescriptor("value", type);
    new PropertyDescriptor("value", type, "getValue", "setValue");
}