List of usage examples for java.beans Introspector getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException
From source file:com.webbfontaine.valuewebb.model.util.Utils.java
public static PropertyDescriptor[] getBeanProperties(Class _class) { try {// w w w .j ava 2 s . c o m BeanInfo bi = Introspector.getBeanInfo(_class); return bi.getPropertyDescriptors(); } catch (IntrospectionException e) { LOGGER.error("", e); } return null; }
From source file:org.agiso.core.i18n.util.I18nUtils.java
private static String findGetterFieldCode(Class<?> c, String field, boolean reflectionCheck) throws IntrospectionException { for (PropertyDescriptor pd : Introspector.getBeanInfo(c).getPropertyDescriptors()) { if (pd.getName().equals(field)) { final Method g = pd.getReadMethod(); if (g != null) { // Jeli jest adnotacja I18n na metodzie odczytujcej pole, to pobieranie // pobieranie jej klucza (okrelonego przez 'value') lub klucza domylnego: if (g.isAnnotationPresent(I18n.class)) { if (g.getAnnotation(I18n.class).value().length() > 0) { return g.getAnnotation(I18n.class).value(); } else { return g.getDeclaringClass().getName() + CODE_SEPARATOR + field; }/*from w w w . j a v a 2s . com*/ } else if (reflectionCheck) { // Pole nie jest opisane adnotacj I18n. Jeli do wyszukania maj by // wykorzystane mechanizmy refleksji, to sprawdzamy interfejsy i nadklas: for (Class<?> i : c.getInterfaces()) { String i18nCode = findGetterFieldCode(i, field, false); if (i18nCode != null) { return i18nCode; } } Class<?> s = c.getSuperclass(); if (s != null) { return findGetterFieldCode(s, field, true); } } } } } if (reflectionCheck) { for (Class<?> i : c.getInterfaces()) { String i18nCode = findGetterFieldCode(i, field, false); if (i18nCode != null) { return i18nCode; } } } return null; }
From source file:org.bibsonomy.plugin.jabref.util.JabRefModelConverter.java
/** * @param bibtex/*from w w w.ja v a2 s . co m*/ * target object * @param entry * source object * @return list of all copied property names */ public static List<String> copyStringPropertiesToBibsonomyModel(final BibTex bibtex, final BibtexEntry entry) { final List<String> knownFields = new ArrayList<String>(50); final BeanInfo info; try { info = Introspector.getBeanInfo(bibtex.getClass()); } catch (IntrospectionException e) { ExceptionUtils.logErrorAndThrowRuntimeException(log, e, "could not introspect"); return knownFields; } final PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); // set all known properties of the BibTex for (PropertyDescriptor pd : descriptors) { if (String.class.equals(pd.getPropertyType()) == false) { continue; } if (present(entry.getField((pd.getName().toLowerCase()))) && !JabRefModelConverter.EXCLUDE_FIELDS.contains(pd.getName().toLowerCase())) { final Object value = entry.getField(pd.getName().toLowerCase()); try { pd.getWriteMethod().invoke(bibtex, value); } catch (Exception e) { ExceptionUtils.logErrorAndThrowRuntimeException(log, e, "could not convert property " + pd.getName()); return knownFields; } knownFields.add(pd.getName()); } } return knownFields; }
From source file:org.rhq.plugins.postgres.PostgresServerComponent.java
protected Object lookupAttributeProperty(Object value, String property) { String[] ps = property.split("\\.", 2); String searchProperty = ps[0]; // Try to use reflection try {/*www . j av a 2 s . c o m*/ 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.jredrain.startup.AgentProcessor.java
private Map<String, String> serializableToMap(Object obj) { if (isEmpty(obj)) { return Collections.EMPTY_MAP; }// www . j a va 2 s . c om Map<String, String> resultMap = new HashMap<String, String>(0); // try { PropertyDescriptor[] pds = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors(); for (int index = 0; pds.length > 1 && index < pds.length; index++) { if (Class.class == pds[index].getPropertyType() || pds[index].getReadMethod() == null) { continue; } Object value = pds[index].getReadMethod().invoke(obj); if (notEmpty(value)) { if (isPrototype(pds[index].getPropertyType())//java() || pds[index].getPropertyType().isPrimitive()// || ReflectUitls.isPrimitivePackageType(pds[index].getPropertyType()) || pds[index].getPropertyType() == String.class) { resultMap.put(pds[index].getName(), value.toString()); } else { resultMap.put(pds[index].getName(), JSON.toJSONString(value)); } } } } catch (Exception e) { e.printStackTrace(); } return resultMap; }
From source file:org.tros.utils.PropertiesInitializer.java
/** * Initialize from properties file if possible. *//*w w w .ja v a2 s . co m*/ private void initializeFromProperties() { try { Properties prop = new Properties(); String propFile = this.getClass().getPackage().getName().replace('.', '/') + '/' + this.getClass().getSimpleName() + ".properties"; java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(propFile); ArrayList<URL> urls = new ArrayList<>(); //HACK: semi sort classpath to put "files" first and "jars" second. //this has an impact once we are workin in tomcat where //the classes in tomcat are not stored in a jar. while (resources.hasMoreElements()) { URL url = resources.nextElement(); if (url.toString().startsWith("file:")) { urls.add(0, url); } else { boolean added = false; for (int ii = 0; !added && ii < urls.size(); ii++) { if (!urls.get(ii).toString().startsWith("file:")) { urls.add(ii, url); added = true; } } if (!added) { urls.add(url); } } } //reverse the list, so that the item found first in the //classpath will be the last one run though and thus //be the one to set the final value Collections.reverse(urls); PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors(); for (URL url : urls) { try { prop.load(url.openStream()); ArrayList<String> propKeys = new ArrayList<>(prop.stringPropertyNames()); for (PropertyDescriptor p : props) { if (p.getWriteMethod() != null && p.getReadMethod() != null && p.getReadMethod().getDeclaringClass() != Object.class) { boolean success = false; String val = prop.getProperty(p.getName()); if (val != null) { Object o = TypeHandler.fromString(p.getPropertyType(), val); if (o == null) { try { o = readValue(val, p.getPropertyType()); } catch (Exception ex) { o = null; LOGGER.warn(null, ex); LOGGER.warn( MessageFormat.format("PropertyName: {0}", new Object[] { val })); } } if (o != null) { p.getWriteMethod().invoke(this, o); success = true; } } if (!success && val != null) { // if (TypeHandler.isEnumeratedType(p)) { //// success = setEnumerated(p, val); // } else { success = setValueHelper(p, val); // } } if (success) { propKeys.remove(p.getName()); } } } for (String key : propKeys) { String value = prop.getProperty(key); setNameValuePair(key, value); } } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException ex) { } catch (IllegalAccessException ex) { LOGGER.warn(null, ex); } } } catch (IOException ex) { } catch (IntrospectionException ex) { LOGGER.warn(null, ex); } }
From source file:com.gdcn.modules.db.jdbc.processor.CamelBeanProcessor.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 www.j ava 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()); } List<PropertyDescriptor> propList = Lists.newArrayList(); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { String propName = prop.getName(); try { Field field = ReflectionUtils.findField(c, propName); if (field != null && !field.isAnnotationPresent(Transient.class)) {//1.field=null 2.Transient?? propList.add(prop); } } catch (SecurityException e) { throw new SQLException("Bean Get Field failed: " + e.getMessage()); } } return propList.toArray(new PropertyDescriptor[propList.size()]); }
From source file:com.kangdainfo.common.util.BeanUtil.java
/** This method takes a JavaBean reset type. * @param o JavaBean object// w ww .j av a2s . com */ public static void beanResetType(Object o) { try { PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors(); for (int pdi = 0; pdi < pds.length; pdi++) { String type = Common.get(pds[pdi].getPropertyType()); if (type.equals("class java.lang.Integer")) { pds[pdi].setValue(pds[pdi].getName(), Common.getInt(pds[pdi].getValue(pds[pdi].getName()))); } else if (type.equals("class java.lang.Long")) { pds[pdi].setValue(pds[pdi].getName(), Common.getLong(pds[pdi].getValue(pds[pdi].getName()))); } else if (type.equals("class java.lang.Double")) { pds[pdi].setValue(pds[pdi].getName(), Common.getNumeric(pds[pdi].getValue(pds[pdi].getName()))); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.rhq.plugins.postgres.PostgresServerComponent.java
public double getObjectProperty(Object object, String name) { try {/*from ww w .ja va 2s .c o m*/ BeanInfo info = Introspector.getBeanInfo(object.getClass()); for (PropertyDescriptor pd : info.getPropertyDescriptors()) { if (pd.getName().equals(name)) { return ((Number) pd.getReadMethod().invoke(object)).doubleValue(); } } } catch (Exception e) { log.error("Error occurred while retrieving property '" + name + "' from object [" + object + "]", e); } return Double.NaN; }
From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java
protected void populateCachedCustomReferenceEntities(final Class entityClass, final CachedCustomReferenceEntity[] cachedEntities, final String[] propertyList, final Object[][] data) throws HibernateException { try {//from w w w . j av a 2s .co m 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<CachedCustomReferenceEntity, 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) { if (data[i][j] instanceof CachedCustomHierarchyReferenceEntity) { setter.invoke(entityObject, new Object[] { entityMapByCache.get(data[i][j]) }); } else 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((CustomReferenceEntity) entityObject); } } catch (Exception e) { log.error(ExceptionUtils.getStackTrace(e)); throw new HibernateException(e); } }