List of usage examples for java.beans Introspector getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException
From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java
private Map<String, Object> getTerms(Object bean, Class<?> mixInClass) throws IntrospectionException, IllegalAccessException, NoSuchFieldException { // define terms from package or type in context final Class<?> beanClass = bean.getClass(); Map<String, Object> termsMap = getAnnotatedTerms(beanClass.getPackage(), beanClass.getPackage().getName()); Map<String, Object> classTermsMap = getAnnotatedTerms(beanClass, beanClass.getName()); Map<String, Object> mixinTermsMap = getAnnotatedTerms(mixInClass, beanClass.getName()); // class terms override package terms termsMap.putAll(classTermsMap);/* w w w . j av a 2 s . c om*/ // mixin terms override class terms termsMap.putAll(mixinTermsMap); final Field[] fields = beanClass.getDeclaredFields(); for (Field field : fields) { final Expose fieldExpose = field.getAnnotation(Expose.class); if (Enum.class.isAssignableFrom(field.getType())) { Map<String, String> map = new LinkedHashMap<String, String>(); termsMap.put(field.getName(), map); if (fieldExpose != null) { map.put(AT_ID, fieldExpose.value()); } map.put(AT_TYPE, AT_VOCAB); final Enum value = (Enum) field.get(bean); final Expose enumValueExpose = getAnnotation(value.getClass().getField(value.name()), Expose.class); // TODO redefine actual enum value to exposed on enum value definition if (enumValueExpose != null) { termsMap.put(value.toString(), enumValueExpose.value()); } else { // might use upperToCamelCase if nothing is exposed final String camelCaseEnumValue = WordUtils .capitalizeFully(value.toString(), new char[] { '_' }).replaceAll("_", ""); termsMap.put(value.toString(), camelCaseEnumValue); } } else { if (fieldExpose != null) { termsMap.put(field.getName(), fieldExpose.value()); } } } // TODO do this recursively for nested beans and collect as long as // nested beans have same vocab // expose getters in context final BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { final Method method = propertyDescriptor.getReadMethod(); final Expose expose = method.getAnnotation(Expose.class); if (expose != null) { termsMap.put(propertyDescriptor.getName(), expose.value()); } } return termsMap; }
From source file:org.grails.beans.support.CachedIntrospectionResults.java
/** * Create a new CachedIntrospectionResults instance for the given class. * @param beanClass the bean class to analyze * @throws BeansException in case of introspection failure *//*from w w w. j av a2 s. c o m*/ private CachedIntrospectionResults(Class<?> beanClass) throws BeansException { try { BeanInfo beanInfo = new ExtendedBeanInfo(Introspector.getBeanInfo(beanClass)); if (beanInfo == null) { // If none of the factories supported the class, fall back to the default beanInfo = (shouldIntrospectorIgnoreBeaninfoClasses ? Introspector.getBeanInfo(beanClass, Introspector.IGNORE_ALL_BEANINFO) : Introspector.getBeanInfo(beanClass)); } this.beanInfo = beanInfo; this.propertyDescriptorCache = new LinkedHashMap<String, PropertyDescriptor>(); // This call is slow so we do it once. PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (Class.class.equals(beanClass) && ("classLoader".equals(pd.getName()) || "protectionDomain".equals(pd.getName()))) { // Ignore Class.getClassLoader() and getProtectionDomain() methods - nobody needs to bind to those continue; } pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd); this.propertyDescriptorCache.put(pd.getName(), pd); } this.typeDescriptorCache = new ConcurrentReferenceHashMap<PropertyDescriptor, TypeDescriptor>(); } catch (IntrospectionException ex) { throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex); } }
From source file:io.coala.enterprise.Fact.java
/** * override and deserialize bean properties as declared in factType * <p>/*w w w. j a va 2s. c o m*/ * TODO detect properties from builder methods: {@code withKey(T value)} * * @param om * @param json * @param factType * @param properties * @return the properties again, to allow chaining * @throws IntrospectionException */ static <T extends Fact> Map<String, Object> fromJSON(final ObjectMapper om, final TreeNode json, final Class<T> factType, final Map<String, Object> properties) { try { final ObjectNode tree = (ObjectNode) json; final BeanInfo beanInfo = Introspector.getBeanInfo(factType); for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) if (tree.has(pd.getName())) properties.computeIfPresent(pd.getName(), (property, current) -> JsonUtil.valueOf(om, tree.get(property), pd.getPropertyType())); return properties; } catch (final Throwable e) { return Thrower.rethrowUnchecked(e); } }
From source file:org.jaffa.util.BeanHelper.java
/** * This will inspect the input beanClass, and obtain the type for the input property. * A null will be returned in case there is no such property. * @return the type for the property./* w ww. j a v a 2 s . c o m*/ * @param beanClass The bean class to be introspected. * @param propertyName The property name. * @throws IntrospectionException if an exception occurs during introspection. */ public static Class getPropertyType(Class beanClass, String propertyName) throws IntrospectionException { BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); if (beanInfo != null) { PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); if (pds != null) { for (PropertyDescriptor pd : pds) { if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) return pd.getPropertyType(); } } } return null; }
From source file:org.apache.openejb.server.axis.assembler.HeavyweightTypeInfoBuilder.java
/** * Map the (nested) fields of a XML Schema Type to Java Beans properties or public fields of the specified Java Class. * * @param javaClass the java class to map * @param xmlTypeInfo the xml schema for the type * @param javaXmlTypeMapping the java to xml type mapping metadata * @param typeInfo the JaxRpcTypeInfo for this type * @throws OpenEJBException if the XML Schema Type can not be mapped to the Java Class *//* www. ja v a 2 s. c om*/ private void mapFields(Class javaClass, XmlTypeInfo xmlTypeInfo, JavaXmlTypeMapping javaXmlTypeMapping, JaxRpcTypeInfo typeInfo) throws OpenEJBException { // Skip arrays since they can't define a variable-mapping element if (!javaClass.isArray()) { // if there is a variable-mapping, log a warning if (!javaXmlTypeMapping.getVariableMapping().isEmpty()) { log.warn("Ignoring variable-mapping defined for class " + javaClass + " which is an array."); } return; } // Index Java bean properties by name Map<String, Class> properties = new HashMap<String, Class>(); try { PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(javaClass).getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { properties.put(propertyDescriptor.getName(), propertyDescriptor.getPropertyType()); } } catch (IntrospectionException e) { throw new OpenEJBException("Class " + javaClass + " is not a valid javabean", e); } for (VariableMapping variableMapping : javaXmlTypeMapping.getVariableMapping()) { String fieldName = variableMapping.getJavaVariableName(); if (variableMapping.getXmlAttributeName() != null) { JaxRpcFieldInfo fieldInfo = new JaxRpcFieldInfo(); fieldInfo.name = fieldName; // verify that the property exists on the java class Class javaType = properties.get(fieldName); if (javaType == null) { throw new OpenEJBException("field name " + fieldName + " not found in " + properties); } String attributeLocalName = variableMapping.getXmlAttributeName(); QName xmlName = new QName("", attributeLocalName); fieldInfo.xmlName = xmlName; fieldInfo.xmlType = xmlTypeInfo.attributes.get(attributeLocalName); if (fieldInfo.xmlType == null) { throw new OpenEJBException( "attribute " + xmlName + " not found in schema " + xmlTypeInfo.qname); } typeInfo.fields.add(fieldInfo); } else { JaxRpcFieldInfo fieldInfo = new JaxRpcFieldInfo(); fieldInfo.isElement = true; fieldInfo.name = fieldName; // verify that the property exists on the java class or there is a public field Class javaType = properties.get(fieldName); if (javaType == null) { //see if it is a public field try { Field field = javaClass.getField(fieldName); javaType = field.getType(); } catch (NoSuchFieldException e) { throw new OpenEJBException("field name " + fieldName + " not found in " + properties, e); } } QName xmlName = new QName("", variableMapping.getXmlElementName()); XmlElementInfo nestedElement = xmlTypeInfo.elements.get(xmlName); if (nestedElement == null) { String ns = xmlTypeInfo.qname.getNamespaceURI(); xmlName = new QName(ns, variableMapping.getXmlElementName()); nestedElement = xmlTypeInfo.elements.get(xmlName); if (nestedElement == null) { throw new OpenEJBException( "element " + xmlName + " not found in schema " + xmlTypeInfo.qname); } } fieldInfo.isNillable = nestedElement.nillable || hasEncoded; fieldInfo.xmlName = xmlName; // xml type if (nestedElement.xmlType != null) { fieldInfo.xmlType = nestedElement.xmlType; } else { QName anonymousName; if (xmlTypeInfo.anonymous) { anonymousName = new QName(xmlTypeInfo.qname.getNamespaceURI(), xmlTypeInfo.qname.getLocalPart() + ">" + nestedElement.qname.getLocalPart()); } else { anonymousName = new QName(xmlTypeInfo.qname.getNamespaceURI(), ">" + xmlTypeInfo.qname.getLocalPart() + ">" + nestedElement.qname.getLocalPart()); } fieldInfo.xmlType = anonymousName; } if (javaType.isArray()) { fieldInfo.minOccurs = nestedElement.minOccurs; fieldInfo.maxOccurs = nestedElement.maxOccurs; } typeInfo.fields.add(fieldInfo); } } }
From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java
Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues, String parentParamName) { if (Map.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Map not supported"); } else if (Collection.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Collection not supported"); } else {/*from www . jav a2 s . c o m*/ try { Constructor[] constructors = clazz.getConstructors(); Constructor constructor = PropertyUtils.findDefaultCtor(constructors); if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } Assert.notNull(constructor, "no default constructor or JsonCreator found"); int parameterCount = constructor.getParameterTypes().length; Object[] args = new Object[parameterCount]; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; String paramName = jsonProperty.value(); List<String> formValue = formValues.get(parentParamName + paramName); Class<?> parameterType = parameters[paramIndex]; if (DataType.isSingleValueType(parameterType)) { if (formValue != null) { if (formValue.size() == 1) { args[paramIndex++] = DataType.asType(parameterType, formValue.get(0)); } else { // // TODO create proper collection type throw new IllegalArgumentException("variable list not supported"); // List<Object> listValue = new ArrayList<Object>(); // for (String item : formValue) { // listValue.add(DataType.asType(parameterType, formValue.get(0))); // } // args[paramIndex++] = listValue; } } else { args[paramIndex++] = null; } } else { args[paramIndex++] = recursivelyCreateObject(parameterType, formValues, parentParamName + paramName + "."); } } } } Assert.isTrue(args.length == paramIndex, "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty"); } Object ret = constructor.newInstance(args); BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method writeMethod = propertyDescriptor.getWriteMethod(); String name = propertyDescriptor.getName(); List<String> strings = formValues.get(name); if (writeMethod != null && strings != null && strings.size() == 1) { writeMethod.invoke(ret, DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor } } return ret; } catch (Exception e) { throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e); } } }
From source file:com.palantir.ptoss.util.Reflections.java
/** * Returns a {@link Function} that will read values from the named field from a passed object. * @param klass type to read values from * @param returnType return type of read field * @param getter name of the field// w w w . java 2 s.c o m * @return a {@link Function} object that, when applied to an instance of <code>klass</code>, returns the * of type <code>returnType</code> that resides in field <code>getter</code> */ public static <F, T> Function<F, T> getterFunction(final Class<F> klass, final Class<T> returnType, String getter) { try { BeanInfo beanInfo = Introspector.getBeanInfo(klass); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); Method method = null; for (PropertyDescriptor descriptor : props) { if (descriptor.getName().equals(getter)) { method = descriptor.getReadMethod(); break; } } if (method == null) { throw new IllegalStateException(); } final Method readMethod = method; return new Function<F, T>() { public T apply(F from) { try { return returnType.cast(readMethod.invoke(from)); } catch (Exception e) { Throwables.throwUncheckedException(e); return null; } } }; } catch (IntrospectionException e) { Throwables.throwUncheckedException(e); return null; } }
From source file:com.kangdainfo.common.util.BeanUtil.java
/** This method takes 2 JavaBeans of the same type and copies the properties of one bean to the other. * Any attempts that have an IllegalAccessException will be ignored. This will also NOT recurse into nested bean * results. References to existing beanage will be includes. Try using .clone() for that stuff. * @param from Source Bean/*from w w w .j a v a 2 s . co m*/ * @param to Desitnation Bean */ public static void copyBeanToBean(Object from, Object to) throws InvocationTargetException, IntrospectionException { PropertyDescriptor[] pds = Introspector.getBeanInfo(from.getClass()).getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { try { if (pds[i].getName().equals("class")) { continue; } Object[] value = { pds[i].getReadMethod().invoke(from) }; if (pds[i].getWriteMethod() != null) pds[i].getWriteMethod().invoke(to, value); } catch (IllegalAccessException iae) { //Im just going to ignore any properties I don't have access too. } } }
From source file:org.bibsonomy.model.util.BibTexUtils.java
/** * return a bibtex string representation of the given bibtex object * /*from w ww . j a v a 2s .com*/ * @param bib - a bibtex object * @param mode - the serializing mode (parse misc fields or include misc fields as they are) * @return String bibtexString * * TODO use BibTex.DEFAULT_OPENBRACKET etc. * */ public static String toBibtexString(final BibTex bib, SerializeBibtexMode mode) { try { final BeanInfo bi = Introspector.getBeanInfo(bib.getClass()); /* * start with entrytype and key */ final StringBuilder buffer = new StringBuilder( "@" + bib.getEntrytype() + "{" + bib.getBibtexKey() + ",\n"); /* * append all other fields */ for (final PropertyDescriptor d : bi.getPropertyDescriptors()) { final Method getter = d.getReadMethod(); // loop over all String attributes final Object o = getter.invoke(bib, (Object[]) null); if (String.class.equals(d.getPropertyType()) && o != null && !EXCLUDE_FIELDS.contains(d.getName())) { /* * Strings containing whitespace give empty fields ... we ignore them */ String value = ((String) o); if (present(value)) { if (!NUMERIC_PATTERN.matcher(value).matches()) { value = DEFAULT_OPENING_BRACKET + value + DEFAULT_CLOSING_BRACKET; } buffer.append(" " + d.getName().toLowerCase() + " = " + value + ",\n"); } } } /* * process miscFields map, if present */ if (present(bib.getMiscFields())) { if (mode.equals(SerializeBibtexMode.PARSED_MISCFIELDS) && !bib.isMiscFieldParsed()) { // parse misc field, if not yet done bib.parseMiscField(); } buffer.append(serializeMiscFields(bib.getMiscFields(), true)); } /* * include plain misc fields if desired */ if (mode.equals(SerializeBibtexMode.PLAIN_MISCFIELDS) && present(bib.getMisc())) { buffer.append(" " + bib.getMisc() + ",\n"); } /* * add month */ final String month = bib.getMonth(); if (present(month)) { // we don't add {}, this is done by getMonth(), if necessary buffer.append(" month = " + getMonth(month) + ",\n"); } /* * add abstract */ final String bibAbstract = bib.getAbstract(); if (present(bibAbstract)) { buffer.append(" abstract = {" + bibAbstract + "},\n"); } /* * remove last comma */ buffer.delete(buffer.lastIndexOf(","), buffer.length()); buffer.append("\n}"); return buffer.toString(); } catch (IntrospectionException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } return null; }
From source file:com.seovic.core.objects.DynamicObject.java
public static Map<String, Object> getPropertyMap(Object obj) { Assert.notNull(obj, "Argument cannot be null"); try {/*w ww. j a v a 2 s. c o m*/ BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); Map<String, Object> propertyMap = new HashMap<String, Object>(propertyDescriptors.length); for (PropertyDescriptor pd : propertyDescriptors) { Method getter = pd.getReadMethod(); if (getter != null) { propertyMap.put(pd.getName(), getter.invoke(obj)); } } return propertyMap; } catch (Exception e) { throw new RuntimeException(e); } }