List of usage examples for java.beans Introspector getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException
From source file:org.hopen.framework.rewrite.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 *//*w w w . ja v a2 s.co m*/ private CachedIntrospectionResults(Class beanClass, boolean cacheFullMetadata) throws BeansException { try { if (logger.isTraceEnabled()) { logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]"); } BeanInfo beanInfo = null; for (BeanInfoFactory beanInfoFactory : beanInfoFactories) { beanInfo = beanInfoFactory.getBeanInfo(beanClass); if (beanInfo != null) { break; } } if (beanInfo == null) { // If none of the factories supported the class, fall back to the default beanInfo = Introspector.getBeanInfo(beanClass); } this.beanInfo = beanInfo; // Immediately remove class from Introspector cache, to allow for proper // garbage collection on class loader shutdown - we cache it here anyway, // in a GC-friendly manner. In contrast to CachedIntrospectionResults, // Introspector does not use WeakReferences as values of its WeakHashMap! Class classToFlush = beanClass; do { Introspector.flushFromCaches(classToFlush); classToFlush = classToFlush.getSuperclass(); } while (classToFlush != null); if (logger.isTraceEnabled()) { logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]"); } 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())) { // Ignore Class.getClassLoader() method - nobody needs to bind to that continue; } if (logger.isTraceEnabled()) { logger.trace("Found bean property '" + pd.getName() + "'" + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]" : "") + (pd.getPropertyEditorClass() != null ? "; editor [" + pd.getPropertyEditorClass().getName() + "]" : "")); } if (cacheFullMetadata) { pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd); } this.propertyDescriptorCache.put(pd.getName(), pd); } } catch (IntrospectionException ex) { throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex); } }
From source file:org.tros.utils.PropertiesInitializer.java
/** * Initialize from properties file if possible. * * @param dir/*from w w w.j a v a 2 s. c om*/ */ private void initializeFromProperties(String dir) { if (dir == null) { return; } Properties prop = new Properties(); String propFile = dir + '/' + this.getClass().getSimpleName() + ".properties"; File f = new File(propFile); if (f.exists()) { try (FileInputStream fis = new FileInputStream(f)) { PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors(); prop.load(fis); 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)) { //// setEnumerated(p, val); // } else { setValueHelper(p, val); // } } } } for (String key : propKeys) { String value = prop.getProperty(key); setNameValuePair(key, value); } } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException ex) { } catch (IllegalAccessException ex) { LOGGER.debug(null, ex); } catch (IntrospectionException ex) { LOGGER.warn(null, ex); } } }
From source file:com.sparkplatform.api.core.PropertyAsserter.java
/** * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Big difference here is that we try to * automatically introspect the target object, finding read/write properties, and automatically testing the getter * and setter. Note specifically that read-only properties are ignored, as there is no way for us to know how to set * the value (since there isn't a public setter). * <p/>/*from w ww. j av a 2 s. co m*/ * Any property names contained in the blacklist will be skipped. * <p/> * * @param target the object on which to invoke the getter and setter * @param propertyNames the list of property names that should not be tested */ public static void assertBasicGetterSetterBehaviorWithBlacklist(Object target, String... propertyNames) { List<String> blacklist = Arrays.asList(propertyNames); try { BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass()); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getWriteMethod() == null) { continue; } if (!blacklist.contains(descriptor.getDisplayName())) { assertBasicGetterSetterBehavior(target, descriptor.getDisplayName()); } } } catch (IntrospectionException e) { fail("Failed while introspecting target " + target.getClass()); } }
From source file:com.espertech.esper.event.bean.PropertyHelper.java
/** * Using the Java Introspector class the method returns the property descriptors obtained through introspection. * @param clazz to introspect//from ww w .j a va 2 s . c om * @return array of property descriptors */ protected static PropertyDescriptor[] introspect(Class clazz) { BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(clazz); } catch (IntrospectionException e) { return (new PropertyDescriptor[0]); } return beanInfo.getPropertyDescriptors(); }
From source file:com.kangdainfo.common.util.BeanUtil.java
/** This method takes a JavaBean and generates a standard toString() type result for it. * @param o JavaBean object to stringinate * @return STRINGIATION! Stringingating the countryside. Stringinating all the peasants. *///from w ww. j a v a2 s.c o m public static String beanToString(Object o) { StringBuffer result = new StringBuffer(); if (o == null) { return "--- null"; } result.append("--- begin"); result.append(o.getClass().getName()); result.append(" hash: "); result.append(o.hashCode()); result.append("\r\n"); try { PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors(); for (int pdi = 0; pdi < pds.length; pdi++) { try { result.append( "Property: " + pds[pdi].getName() + " Value: " + pds[pdi].getReadMethod().invoke(o)); } catch (IllegalAccessException iae) { result.append("Property: " + pds[pdi].getName() + " (Illegal Access to Value) "); } catch (InvocationTargetException iae) { result.append( "Property: " + pds[pdi].getName() + " (InvocationTargetException) " + iae.toString()); } catch (Exception e) { result.append("Property: " + pds[pdi].getName() + " (Other Exception )" + e.toString()); } result.append("\r\n"); } } catch (IntrospectionException ie) { result.append("Introspection Exception: " + ie.toString()); result.append("\r\n"); } result.append("--- end "); result.append(o.getClass().getName()); result.append(" hash: "); result.append(o.hashCode()); result.append("\n"); return result.toString(); }
From source file:BeanVector.java
/** * This method does a string match on values of a property. * @param propertyName String value containing the name of the property to match. * @param match Value to search for. This is a case-insensitive value that takes % as a multiple character wildcard value. * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception * @return a new BeanVector filtered on the specified property *///from w ww. j av a 2 s . co m public BeanVector<T> getFilteredStringMatch(String propertyName, String match) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { Hashtable cache = new Hashtable(); String currentClass = ""; PropertyDescriptor pd = null; BeanVector<T> results = new BeanVector<T>(); for (int i = 0; i < this.size(); i++) { T o = this.elementAt(i); if (!currentClass.equals(o.getClass().getName())) { pd = (PropertyDescriptor) cache.get(o.getClass().getName()); if (pd == null) { 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]; cache.put(o.getClass().getName(), pd); foundProperty = true; } } } } String value = pd.getReadMethod().invoke(o).toString().toLowerCase(); StringTokenizer st = new StringTokenizer(match.toLowerCase(), "%"); boolean isMatch = true; int matchIndex = 0; while (st.hasMoreTokens() && isMatch) { String tk = st.nextToken(); if (value.indexOf(tk, matchIndex) == -1) { isMatch = false; } else { matchIndex = value.indexOf(tk, matchIndex) + tk.length(); } } if (isMatch) { results.add(o); } } return results; }
From source file:BeanArrayList.java
/** * This method does a string match on values of a property. * @param propertyName String value containing the name of the property to match. * @param match Value to search for. This is a case-insensitive value that takes % as a multiple character wildcard value. * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception * @return a new BeanArrayList filtered on the specified property *//* w ww .j a v a 2 s. com*/ public BeanArrayList<T> getFilteredStringMatch(String propertyName, String match) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { HashMap cache = new HashMap(); String currentClass = ""; PropertyDescriptor pd = null; BeanArrayList<T> results = new BeanArrayList<T>(); for (int i = 0; i < this.size(); i++) { T o = this.get(i); if (!currentClass.equals(o.getClass().getName())) { pd = (PropertyDescriptor) cache.get(o.getClass().getName()); if (pd == null) { 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]; cache.put(o.getClass().getName(), pd); foundProperty = true; } } } } String value = pd.getReadMethod().invoke(o).toString().toLowerCase(); StringTokenizer st = new StringTokenizer(match.toLowerCase(), "%"); boolean isMatch = true; int matchIndex = 0; while (st.hasMoreTokens() && isMatch) { String tk = st.nextToken(); if (value.indexOf(tk, matchIndex) == -1) { isMatch = false; } else { matchIndex = value.indexOf(tk, matchIndex) + tk.length(); } } if (isMatch) { results.add(o); } } return results; }
From source file:ReflectUtil.java
/** * Fetches the property descriptor for the named property of the supplied class. To * speed things up a cache is maintained of propertyName to PropertyDescriptor for * each class used with this method. If there is no property with the specified name, * returns null./* ww w .j a v a 2 s . co m*/ * * @param clazz the class who's properties to examine * @param property the String name of the property to look for * @return the PropertyDescriptor or null if none is found with a matching name */ public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String property) { Map<String, PropertyDescriptor> pds = propertyDescriptors.get(clazz); if (pds == null) { try { BeanInfo info = Introspector.getBeanInfo(clazz); PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); pds = new HashMap<String, PropertyDescriptor>(); for (PropertyDescriptor descriptor : descriptors) { pds.put(descriptor.getName(), descriptor); } propertyDescriptors.put(clazz, pds); } catch (IntrospectionException ie) { throw new RuntimeException("Could not examine class '" + clazz.getName() + "' using Introspector.getBeanInfo() to determine property information.", ie); } } return pds.get(property); }
From source file:com.liusoft.dlog4j.search.SearchProxy.java
/** * /*from w w w. j a v a 2s . c o m*/ * @param obj * @param field * @param value * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws IntrospectionException * @throws InstantiationException */ private static void setNestedProperty(Object obj, String field, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IntrospectionException, InstantiationException { StringTokenizer st = new StringTokenizer(field, "."); Class nodeClass = obj.getClass(); StringBuffer tmp_prop = new StringBuffer(); while (st.hasMoreElements()) { String f = st.nextToken(); if (tmp_prop.length() > 0) tmp_prop.append('.'); tmp_prop.append(f); PropertyDescriptor[] props = Introspector.getBeanInfo(nodeClass).getPropertyDescriptors(); for (int i = 0; i < props.length; i++) { if (props[i].getName().equals(f)) { if (PropertyUtils.getNestedProperty(obj, tmp_prop.toString()) == null) { nodeClass = props[i].getPropertyType(); PropertyUtils.setNestedProperty(obj, f, nodeClass.newInstance()); } continue; } } } PropertyUtils.setNestedProperty(obj, field, value); }