List of usage examples for java.beans Introspector getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException
From source file:ch.rasc.extclassgenerator.ModelGenerator.java
public static ModelBean createModel(final Class<?> clazz, final OutputConfig outputConfig) { Assert.notNull(clazz, "clazz must not be null"); Assert.notNull(outputConfig.getIncludeValidation(), "includeValidation must not be null"); ModelCacheKey key = new ModelCacheKey(clazz.getName(), outputConfig); SoftReference<ModelBean> modelReference = modelCache.get(key); if (modelReference != null && modelReference.get() != null) { return modelReference.get(); }/*w ww . jav a 2s .co m*/ Model modelAnnotation = clazz.getAnnotation(Model.class); final ModelBean model = new ModelBean(); if (modelAnnotation != null && StringUtils.hasText(modelAnnotation.value())) { model.setName(modelAnnotation.value()); } else { model.setName(clazz.getName()); } if (modelAnnotation != null) { model.setAutodetectTypes(modelAnnotation.autodetectTypes()); } if (modelAnnotation != null) { model.setExtend(modelAnnotation.extend()); model.setIdProperty(modelAnnotation.idProperty()); model.setVersionProperty(trimToNull(modelAnnotation.versionProperty())); model.setPaging(modelAnnotation.paging()); model.setDisablePagingParameters(modelAnnotation.disablePagingParameters()); model.setCreateMethod(trimToNull(modelAnnotation.createMethod())); model.setReadMethod(trimToNull(modelAnnotation.readMethod())); model.setUpdateMethod(trimToNull(modelAnnotation.updateMethod())); model.setDestroyMethod(trimToNull(modelAnnotation.destroyMethod())); model.setMessageProperty(trimToNull(modelAnnotation.messageProperty())); model.setWriter(trimToNull(modelAnnotation.writer())); model.setReader(trimToNull(modelAnnotation.reader())); model.setSuccessProperty(trimToNull(modelAnnotation.successProperty())); model.setTotalProperty(trimToNull(modelAnnotation.totalProperty())); model.setRootProperty(trimToNull(modelAnnotation.rootProperty())); model.setWriteAllFields(modelAnnotation.writeAllFields()); model.setIdentifier(trimToNull(modelAnnotation.identifier())); String clientIdProperty = trimToNull(modelAnnotation.clientIdProperty()); if (StringUtils.hasText(clientIdProperty)) { model.setClientIdProperty(clientIdProperty); model.setClientIdPropertyAddToWriter(true); } else { model.setClientIdProperty(null); model.setClientIdPropertyAddToWriter(false); } } final Set<String> hasReadMethod = new HashSet<String>(); BeanInfo bi; try { bi = Introspector.getBeanInfo(clazz); } catch (IntrospectionException e) { throw new RuntimeException(e); } for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { if (pd.getReadMethod() != null && pd.getReadMethod().getAnnotation(JsonIgnore.class) == null) { hasReadMethod.add(pd.getName()); } } if (clazz.isInterface()) { final List<Method> methods = new ArrayList<Method>(); ReflectionUtils.doWithMethods(clazz, new MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { methods.add(method); } }); Collections.sort(methods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); for (Method method : methods) { createModelBean(model, method, outputConfig); } } else { final Set<String> fields = new HashSet<String>(); Set<ModelField> modelFieldsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelFields.class, ModelField.class); for (ModelField modelField : modelFieldsOnType) { if (StringUtils.hasText(modelField.value())) { ModelFieldBean modelFieldBean; if (StringUtils.hasText(modelField.customType())) { modelFieldBean = new ModelFieldBean(modelField.value(), modelField.customType()); } else { modelFieldBean = new ModelFieldBean(modelField.value(), modelField.type()); } updateModelFieldBean(modelFieldBean, modelField); model.addField(modelFieldBean); } } Set<ModelAssociation> modelAssociationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelAssociations.class, ModelAssociation.class); for (ModelAssociation modelAssociationAnnotation : modelAssociationsOnType) { AbstractAssociation modelAssociation = AbstractAssociation .createAssociation(modelAssociationAnnotation); if (modelAssociation != null) { model.addAssociation(modelAssociation); } } Set<ModelValidation> modelValidationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelValidations.class, ModelValidation.class); for (ModelValidation modelValidationAnnotation : modelValidationsOnType) { AbstractValidation modelValidation = AbstractValidation.createValidation( modelValidationAnnotation.propertyName(), modelValidationAnnotation, outputConfig.getIncludeValidation()); if (modelValidation != null) { model.addValidation(modelValidation); } } ReflectionUtils.doWithFields(clazz, new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if (!fields.contains(field.getName()) && (field.getAnnotation(ModelField.class) != null || field.getAnnotation(ModelAssociation.class) != null || (Modifier.isPublic(field.getModifiers()) || hasReadMethod.contains(field.getName())) && field.getAnnotation(JsonIgnore.class) == null)) { // ignore superclass declarations of fields already // found in a subclass fields.add(field.getName()); createModelBean(model, field, outputConfig); } } }); } modelCache.put(key, new SoftReference<ModelBean>(model)); return model; }
From source file:org.liveSense.api.beanprocessors.DbStandardBeanProcessor.java
/** * Returns a PropertyDescriptor[] for the given Class. * * @param c The Class to retrieve PropertyDescriptors for. * @return A PropertyDescriptor[] describing the Class. * @throws SQLException if introspection failed. *///from w ww . j a v a 2 s . co m private PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException { // Introspector caches BeanInfo classes for better performance BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(c); } catch (IntrospectionException e) { throw new SQLException("Bean introspection failed: " + e.getMessage()); } // PropertyDescriptor[] pd = beanInfo.getPropertyDescriptors(); return beanInfo.getPropertyDescriptors(); }
From source file:es.logongas.ix3.web.json.impl.JsonReaderImplEntityJackson.java
/** * Establece el valor de la propiedad de un Bean * * @param obj El objeto Bean//from w w w . jav a2s .c om * @param value El valor de la propiedad * @param propertyName El nombre de la propiedad */ private void setValueToBean(Object obj, Object value, String propertyName) { try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); Method writeMethod = null; for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals(propertyName)) { writeMethod = propertyDescriptor.getWriteMethod(); } } if (writeMethod == null) { throw new RuntimeException( "No existe la propiedad:" + propertyName + " en " + obj.getClass().getName()); } writeMethod.invoke(obj, value); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:org.rhq.plugins.jmx.MBeanResourceComponent.java
protected Object lookupAttributeProperty(Object value, String property) { String[] ps = property.split("\\.", 2); String searchProperty = ps[0]; // Values returned from EMS connections may be from JMX classes loaded in separate classloaders (for server compatibility) // so we use reflection to be able to handle any instance of the CompositeData class. Class[] interfaces = value.getClass().getInterfaces(); boolean isCompositeData = false; for (Class intf : interfaces) { if (intf.getName().equals(CompositeData.class.getName())) { isCompositeData = true;//from w w w .j ava2 s. c o m } } if (value.getClass().getName().equals(CompositeData.class.getName()) || isCompositeData) { try { Method m = value.getClass().getMethod("get", String.class); value = m.invoke(value, ps[1]); } catch (NoSuchMethodException e) { /* Won't happen */ } catch (Exception e) { log.info("Unable to read attribute property [" + property + "] from composite data value", e); } } else { // Try to use reflection try { PropertyDescriptor[] pds = Introspector.getBeanInfo(value.getClass()).getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (pd.getName().equals(searchProperty)) { value = pd.getReadMethod().invoke(value); } } } catch (Exception e) { log.debug("Unable to read property from measurement attribute [" + searchProperty + "] not found on [" + this.resourceContext.getResourceKey() + "]"); } } if (ps.length > 1) { value = lookupAttributeProperty(value, ps[1]); } return value; }
From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java
protected void populateCachedReferenceEntities(final Class entityClass, final CachedReferenceEntity[] cachedEntities, final String[] propertyList, final Object[][] data) throws HibernateException { try {//from w ww .j a v a 2 s .c om final Hashtable pdsByName = new Hashtable(); final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass); final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { final PropertyDescriptor descriptor = descriptors[i]; if (descriptor.getWriteMethod() != null) pdsByName.put(descriptor.getName(), descriptor.getWriteMethod()); } Map entityMapByCache = new HashMap<CachedReferenceEntity, Object>(); for (int i = 0; i < data.length; i++) { final Object entityObject = entityClass.newInstance(); for (int j = 0; j < propertyList.length; j++) { final Method setter = (Method) pdsByName.get(propertyList[j]); if (setter != null && data[i][j] != null) { setter.invoke(entityObject, new Object[] { data[i][j] }); } } entityMapByCache.put(cachedEntities[i], entityObject); if (!useEjb) session.save(entityObject); else entityManager.persist(entityObject); cachedEntities[i].setEntity((ReferenceEntity) entityObject); } } catch (Exception e) { log.error(e); throw new HibernateException(e); } }
From source file:es.logongas.ix3.web.json.impl.JsonWriterImplEntityJackson.java
/** * Obtiene el valor de la propiedad de un Bean * * @param obj El objeto Bean/*from w w w. j a v a 2 s. com*/ * @param propertyName El nombre de la propiedad * @return El valor de la propiedad */ private Object getValueFromBean(Object obj, String propertyName) { try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); Method readMethod = null; for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals(propertyName)) { readMethod = propertyDescriptor.getReadMethod(); break; } } if (readMethod == null) { throw new RuntimeException( "No existe la propiedad:" + propertyName + " en la clase " + obj.getClass().getName()); } return readMethod.invoke(obj); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java
public static Set<String> getBeanPropertyNames(Class<?> beanClass) { Set<String> result = new HashSet<>(); BeanInfo beanInfo = null;/*from www . j a va 2s . c o m*/ try { beanInfo = Introspector.getBeanInfo(beanClass); } catch (IntrospectionException ex) { Logger.getLogger(LumpiUtil.class.getName()).log(Level.SEVERE, null, ex); } finally { if (beanInfo != null) { PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); if (ArrayUtils.isNotEmpty(propertyDescriptors)) { for (PropertyDescriptor pd : propertyDescriptors) { result.add(pd.getName()); } } } } return result; }
From source file:de.xwic.appkit.core.transport.xml.XmlBeanSerializer.java
/** * Deserializes an element into a bean./*from w ww .ja v a2s. c o m*/ * * @param elm * @param context * @return * @throws TransportException */ public void deserializeBean(Object bean, Element elm, Map<EntityKey, Integer> context, boolean forceLoadCollection) throws TransportException { // now read the properties try { BeanInfo bi = Introspector.getBeanInfo(bean.getClass()); for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { Method mWrite = pd.getWriteMethod(); if (!"class".equals(pd.getName()) && mWrite != null && !skipPropertyNames.contains(pd.getName())) { Element elmProp = elm.element(pd.getName()); if (elmProp != null) { Object value = readValue(context, elmProp, pd, forceLoadCollection); mWrite.invoke(bean, new Object[] { value }); } else { log.warn("The property " + pd.getName() + " is not specified in the xml document. The bean may not be restored completly"); } } } } catch (Exception e) { throw new TransportException("Error deserializing bean: " + e, e); } }
From source file:BeanArrayList.java
/** * This method returns the sum of all values of a numerical * property.// ww w .j ava 2s . c o m * @param propertyName String value of the property name to calculate. * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception * @return sum of a numerical property */ public Number getSumOfProperty(String propertyName) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { double d = 0.0; String currentClass = ""; PropertyDescriptor pd = null; for (int i = 0; i < this.size(); i++) { T o = this.get(i); if (!currentClass.equals(o.getClass().getName())) { PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors(); boolean foundProperty = false; for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) { if (pds[pdi].getName().equals(propertyName)) { pd = pds[pdi]; foundProperty = true; } } } if (o != null) { Number n = (Number) pd.getReadMethod().invoke(o); d += n.doubleValue(); } } return new Double(d); }
From source file:BeanVector.java
/** * This method returns the sum of all values of a numerical * property.//from w w w .ja va2 s .c om * @param propertyName String value of the property name to calculate. * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception * @return sum of a numerical property */ public Number getSumOfProperty(String propertyName) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { double d = 0.0; String currentClass = ""; PropertyDescriptor pd = null; for (int i = 0; i < this.size(); i++) { T o = this.elementAt(i); if (!currentClass.equals(o.getClass().getName())) { PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors(); boolean foundProperty = false; for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) { if (pds[pdi].getName().equals(propertyName)) { pd = pds[pdi]; foundProperty = true; } } } if (o != null) { Number n = (Number) pd.getReadMethod().invoke(o); d += n.doubleValue(); } } return new Double(d); }