List of usage examples for java.beans Introspector getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException
From source file:org.loy.fesf.core.impl.BaseContext.java
/** * <p>/* w w w . j a va 2 s. co m*/ * Customize the contents of our underlying <code>Map</code> so that it * contains keys corresponding to all of the JavaBeans properties of the * {@link Context}implementation class. * </p> * */ private void init() { // Retrieve the set of property descriptors for this Context class try { this.pd = Introspector.getBeanInfo(getClass()).getPropertyDescriptors(); } catch (IntrospectionException e) { this.pd = new PropertyDescriptor[0]; // Should never happen } removePropertyDescriptor("class"); // Because of "getClass()" removePropertyDescriptor("empty"); // Because of "isEmpty()" // Initialize the underlying Map contents if (this.pd.length > 0) { this.descriptors = new HashMap(); for (int i = 0; i < this.pd.length; i++) { this.descriptors.put(pd[i].getName(), pd[i]); this.localMap.put(pd[i].getName(), BaseContext.SINGLETON); } } }
From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java
/** * Helper method to lookup getter methods for each annotated Field * /*from w ww.jav a 2s . c o m*/ * Note: This requires a proper bean pattern getter method in the annotatedClass for the annotatedField. * * @param annotatedClass * @param annotatedFields * @return */ private ImmutableMap<Field, Method> fieldsToGetterMap(final Class<?> annotatedClass, final ImmutableSet<Field> annotatedFields) { final ImmutableMap.Builder<Field, Method> mappings = new ImmutableMap.Builder<Field, Method>(); final BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(annotatedClass); } catch (IntrospectionException e) { // should never happen LOG.error(e); throw new RuntimeException(e); } final ArrayList<PropertyDescriptor> propertyDescriptors = Lists .newArrayList(beanInfo.getPropertyDescriptors()); for (final Field field : annotatedFields) { for (int i = 0; i < propertyDescriptors.size(); i++) { if (field.getName().equals(propertyDescriptors.get(i).getName())) { mappings.put(field, propertyDescriptors.get(i).getReadMethod()); propertyDescriptors.remove(i); i--; } } } return mappings.build(); }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private static final Set<PropertyDescriptor> initClassMapping(String className) throws ClassNotFoundException, IntrospectionException, PersistenceException { Set<PropertyDescriptor> ids = new HashSet<PropertyDescriptor>(); Set<PropertyDescriptor> collections = new HashSet<PropertyDescriptor>(); Set<PropertyDescriptor> lazys = new HashSet<PropertyDescriptor>(); Set<PropertyDescriptor> eagers = new HashSet<PropertyDescriptor>(); Set<LinkFileInfo> linkedFiles = new HashSet<LinkFileInfo>(); idsByClassName.put(className, ids);//from w ww .j a va2s .com collectionsByClassName.put(className, collections); lazysByClassName.put(className, lazys); eagerObjectsByClassName.put(className, eagers); linkedFilesByClassName.put(className, linkedFiles); List<String> idsAttributes = new ArrayList<String>(); Class<?> c = Class.forName(className); Table tableAnn = c.getAnnotation(Table.class); if (tableAnn != null) { tableByClassName.put(className, tableAnn.name()); } else { Entity entityAnn = c.getAnnotation(Entity.class); if (entityAnn.name() != null) { tableByClassName.put(className, entityAnn.name()); } else { tableByClassName.put(className, className.substring(className.lastIndexOf(".") + 1)); } } BeanInfo beanInfo = Introspector.getBeanInfo(c); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); propertyDescriptorsByClassName.put(className, pds); IdClass idClass = c.getAnnotation(IdClass.class); for (Field f : c.getDeclaredFields()) { Id id = f.getAnnotation(Id.class); if (id != null) { idsAttributes.add(f.getName()); if (f.isAnnotationPresent(GeneratedValue.class)) { generatedIdClasses.add(className); } } } if (!idsAttributes.isEmpty()) { for (Field f : c.getDeclaredFields()) { if (!Modifier.isStatic(f.getModifiers())) { PropertyDescriptor pd = getPropertyDescriptor(pds, f); processField(className, pd, ids, collections, lazys, eagers, f); } } if (idClass != null) { Class clazz = idClass.value(); for (Field f : clazz.getDeclaredFields()) { if (!Modifier.isStatic(f.getModifiers())) { PropertyDescriptor pd = getPropertyDescriptor(pds, f); processField(clazz.getName(), pd, ids, collections, lazys, eagers, f); } } } /*for(PropertyDescriptor pd : pds) { processLinkedFiles(pds, linkedFiles, pd); }*/ } else { for (PropertyDescriptor pd : pds) { processMethod(className, pds, ids, collections, lazys, eagers, linkedFiles, pd); } if (idClass != null) { Class clazz = idClass.value(); for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) { processMethod(clazz.getName(), pds, ids, collections, lazys, eagers, linkedFiles, pd); } } } return ids; }
From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java
private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException { JSONArray arr = new JSONArray(); TypeDiscoverer td = new TypeDiscoverer(); try {//w ww . j a va 2 s . c om for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) { Method readMethod = pd.getReadMethod(); if (readMethod != null) { if (readMethod.getDeclaringClass() == java.lang.Enum.class) { // skip getDeclaringClass continue; } else if ("class".equals(pd.getName())) { // skip getClass continue; } } else { // yields com.datatorrent.api.Context on JDK6 and com.datatorrent.api.Context.OperatorContext with JDK7 if ("up".equals(pd.getName()) && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) { continue; } } //LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType()); Class<?> propertyType = pd.getPropertyType(); if (propertyType != null) { JSONObject propertyObj = new JSONObject(); propertyObj.put("name", pd.getName()); propertyObj.put("canGet", readMethod != null); propertyObj.put("canSet", pd.getWriteMethod() != null); if (readMethod != null) { for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { OperatorClassInfo oci = classInfo.get(c.getName()); if (oci != null) { MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName()); if (getMethodInfo != null) { addTagsToProperties(getMethodInfo, propertyObj); break; } } } // type can be a type symbol or parameterized type td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj); } else { if (pd.getWriteMethod() != null) { td.setTypeArguments(clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj); } } //if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) { // propertyObj.put("properties", getClassProperties(propertyType, level + 1)); //} arr.put(propertyObj); } } } catch (JSONException ex) { throw new RuntimeException(ex); } return arr; }
From source file:org.mypsycho.beans.PropertyUtilsBean.java
/** * <p>// www . j a v a2 s . co m * Retrieve the property descriptors for the specified class, introspecting * and caching them the first time a particular bean class is encountered. * </p> * * @param beanClass Bean class for which property descriptors are requested * @return the property descriptors * @exception IllegalArgumentException if <code>beanClass</code> is null */ public PropertyDescriptor[] createDescriptorsCache(Class<?> beanClass) throws IntrospectionException { // Introspect the bean and cache the generated descriptors BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); if (descriptors == null) { return new PropertyDescriptor[0]; } // ----------------- Workaround for Bug 28358 --------- START ------------------ // // The following code fixes an issue where IndexedPropertyDescriptor // behaves // Differently in different versions of the JDK for 'indexed' properties // which use java.util.List (rather than an array). // // If you have a Bean with the following getters/setters for an indexed // property: // // public List getFoo() // public Object getFoo(int index) // public void setFoo(List foo) // public void setFoo(int index, Object foo) // // then the IndexedPropertyDescriptor's getReadMethod() and // getWriteMethod() // behave as follows: // // JDK 1.3.1_04: returns valid Method objects from these methods. // JDK 1.4.2_05: returns null from these methods. // for (PropertyDescriptor descriptor2 : descriptors) { if (!(descriptor2 instanceof IndexedPropertyDescriptor)) { continue; } IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor) descriptor2; String propName = descriptor.getName().substring(0, 1).toUpperCase() + descriptor.getName().substring(1); if (descriptor.getReadMethod() == null) { String methodName = (descriptor.getIndexedReadMethod() != null) ? descriptor.getIndexedReadMethod().getName() : "get" + propName; Method readMethod = MethodUtils.getMatchingAccessibleMethod(beanClass, methodName, EMPTY_CLASS_PARAMETERS); if (readMethod != null) { try { descriptor.setReadMethod(readMethod); } catch (Exception e) { notify("copy", "Fail to set indexed property" + propName, e); } } } if (descriptor.getWriteMethod() == null) { Method indexedMethod = descriptor.getIndexedWriteMethod(); String methodName = indexedMethod != null ? indexedMethod.getName() : "set" + propName; Method writeMethod = MethodUtils.getMatchingAccessibleMethod(beanClass, methodName, LIST_CLASS_PARAMETER); if (writeMethod == null) { Method[] methods = beanClass.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1 && List.class.isAssignableFrom(parameterTypes[0])) { writeMethod = method; break; } } } } if (writeMethod != null) { try { descriptor.setWriteMethod(writeMethod); } catch (Exception e) { notify("copy", "Fail to set indexed property" + propName, e); } } } } // ----------------- Workaround for Bug 28358 ---------- END ------------------- return descriptors; }
From source file:BeanArrayList.java
/** * performs a selection sort on all the beans in the ArrayList by * PropertyName/*from w ww . j a v a2 s .c om*/ * * <p>You can use a mixture of bean classes as long as all the beans * support the same property (getName() for instance), and all have the * same return type, or can be compareTo()ed each other.</p> * * <p>For optimal performance, it is recommended that if you have a * mixed class set the you have them grouped with like classes together * as this will minimize reflection inspections.</p> * @param propertyName String value containing the property to sort on. * @param ascending == sorts up if true, down if not. * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception */ public synchronized void sortOnProperty(String propertyName, boolean ascending) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { T[] old = null; if ((this.indexPropertyName != null) && (this.changes != null)) { old = this.toTypedArray(); } T temp = null; String currentClass = ""; PropertyDescriptor pd = null; HashMap cache = new HashMap(); for (int i = 0; i < (this.size() - 1); i++) { for (int j = i + 1; j < this.size(); j++) { T o1 = this.get(i); if (!currentClass.equals(o1.getClass().getName())) { pd = (PropertyDescriptor) cache.get(o1.getClass().getName()); if (pd == null) { PropertyDescriptor[] pds = Introspector.getBeanInfo(o1.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(o1.getClass().getName(), pd); foundProperty = true; } } } } //System.out.println( "o1: "+o1+" "+pd); //System.out.println( propertyName +" "+ (pd == null )); Comparable oc1 = (Comparable) pd.getReadMethod().invoke(o1); T o2 = this.get(j); if (!currentClass.equals(o2.getClass().getName())) { pd = (PropertyDescriptor) cache.get(o2.getClass().getName()); if (pd == null) { PropertyDescriptor[] pds = Introspector.getBeanInfo(o2.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; } } } } Comparable oc2 = (Comparable) pd.getReadMethod().invoke(o2); if (ascending) { if ((oc1 != oc2) && ((oc2 == null) || ((oc1 != null) && (oc2 != null) && (oc2.compareTo(oc1) < 0)))) { //swap this.setElementAt(o2, i); this.setElementAt(o1, j); } } else { if ((oc1 != oc2) && ((oc1 == null) || ((oc1 != null) && (oc2 != null) && (oc1.compareTo(oc2) < 0)))) { //swap this.setElementAt(o2, i); this.setElementAt(o1, j); } } } if (old != null) { changes.firePropertyChange(this.indexPropertyName, old, this.toTypedArray()); } } }
From source file:BeanVector.java
/** * performs a selection sort on all the beans in the Vector by * PropertyName/* w w w.ja v a 2s .co m*/ * * <p>You can use a mixture of bean classes as long as all the beans * support the same property (getName() for instance), and all have the * same return type, or can be compareTo()ed each other.</p> * * <p>For optimal performance, it is recommended that if you have a * mixed class set the you have them grouped with like classes together * as this will minimize reflection inspections.</p> * @param propertyName String value containing the property to sort on. * @param ascending == sorts up if true, down if not. * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception */ public synchronized void sortOnProperty(String propertyName, boolean ascending) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { T[] old = null; if ((this.indexPropertyName != null) && (this.changes != null)) { old = this.toTypedArray(); } T temp = null; String currentClass = ""; PropertyDescriptor pd = null; Hashtable cache = new Hashtable(); for (int i = 0; i < (this.size() - 1); i++) { for (int j = i + 1; j < this.size(); j++) { T o1 = this.elementAt(i); if (!currentClass.equals(o1.getClass().getName())) { pd = (PropertyDescriptor) cache.get(o1.getClass().getName()); if (pd == null) { PropertyDescriptor[] pds = Introspector.getBeanInfo(o1.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(o1.getClass().getName(), pd); foundProperty = true; } } } } //System.out.println( "o1: "+o1+" "+pd); //System.out.println( propertyName +" "+ (pd == null )); Comparable oc1 = (Comparable) pd.getReadMethod().invoke(o1); T o2 = this.elementAt(j); if (!currentClass.equals(o2.getClass().getName())) { pd = (PropertyDescriptor) cache.get(o2.getClass().getName()); if (pd == null) { PropertyDescriptor[] pds = Introspector.getBeanInfo(o2.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; } } } } Comparable oc2 = (Comparable) pd.getReadMethod().invoke(o2); if (ascending) { if ((oc1 != oc2) && ((oc2 == null) || ((oc1 != null) && (oc2 != null) && (oc2.compareTo(oc1) < 0)))) { //swap this.setElementAt(o2, i); this.setElementAt(o1, j); } } else { if ((oc1 != oc2) && ((oc1 == null) || ((oc1 != null) && (oc2 != null) && (oc1.compareTo(oc2) < 0)))) { //swap this.setElementAt(o2, i); this.setElementAt(o1, j); } } } if (old != null) { changes.firePropertyChange(this.indexPropertyName, old, this.toTypedArray()); } } }
From source file:org.enerj.apache.commons.beanutils.PropertyUtilsBean.java
/** * <p>Retrieve the property descriptors for the specified class, * introspecting and caching them the first time a particular bean class * is encountered.</p>/*from w w w.j av a 2s . com*/ * * <p><strong>FIXME</strong> - Does not work with DynaBeans.</p> * * @param beanClass Bean class for which property descriptors are requested * * @exception IllegalArgumentException if <code>beanClass</code> is null */ public PropertyDescriptor[] getPropertyDescriptors(Class beanClass) { if (beanClass == null) { throw new IllegalArgumentException("No bean class specified"); } // Look up any cached descriptors for this bean class PropertyDescriptor descriptors[] = null; descriptors = (PropertyDescriptor[]) descriptorsCache.get(beanClass); if (descriptors != null) { return (descriptors); } // Introspect the bean and cache the generated descriptors BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(beanClass); } catch (IntrospectionException e) { return (new PropertyDescriptor[0]); } descriptors = beanInfo.getPropertyDescriptors(); if (descriptors == null) { descriptors = new PropertyDescriptor[0]; } descriptorsCache.put(beanClass, descriptors); return (descriptors); }
From source file:org.evergreen.web.utils.beanutils.PropertyUtilsBean.java
/** * <p>Retrieve the property descriptors for the specified class, * introspecting and caching them the first time a particular bean class * is encountered.</p>/*from w ww.j a v a2s.c o m*/ * * <p><strong>FIXME</strong> - Does not work with DynaBeans.</p> * * @param beanClass Bean class for which property descriptors are requested * @return the property descriptors * * @exception IllegalArgumentException if <code>beanClass</code> is null */ public PropertyDescriptor[] getPropertyDescriptors(Class beanClass) { if (beanClass == null) { throw new IllegalArgumentException("No bean class specified"); } // Look up any cached descriptors for this bean class PropertyDescriptor[] descriptors = null; descriptors = (PropertyDescriptor[]) descriptorsCache.get(beanClass); if (descriptors != null) { return (descriptors); } // Introspect the bean and cache the generated descriptors BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(beanClass); } catch (IntrospectionException e) { return (new PropertyDescriptor[0]); } descriptors = beanInfo.getPropertyDescriptors(); if (descriptors == null) { descriptors = new PropertyDescriptor[0]; } // ----------------- Workaround for Bug 28358 --------- START ------------------ // // The following code fixes an issue where IndexedPropertyDescriptor behaves // Differently in different versions of the JDK for 'indexed' properties which // use java.util.List (rather than an array). // // If you have a Bean with the following getters/setters for an indexed property: // // public List getFoo() // public Object getFoo(int index) // public void setFoo(List foo) // public void setFoo(int index, Object foo) // // then the IndexedPropertyDescriptor's getReadMethod() and getWriteMethod() // behave as follows: // // JDK 1.3.1_04: returns valid Method objects from these methods. // JDK 1.4.2_05: returns null from these methods. // for (int i = 0; i < descriptors.length; i++) { if (descriptors[i] instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor) descriptors[i]; String propName = descriptor.getName().substring(0, 1).toUpperCase() + descriptor.getName().substring(1); if (descriptor.getReadMethod() == null) { String methodName = descriptor.getIndexedReadMethod() != null ? descriptor.getIndexedReadMethod().getName() : "get" + propName; Method readMethod = MethodUtils.getMatchingAccessibleMethod(beanClass, methodName, EMPTY_CLASS_PARAMETERS); if (readMethod != null) { try { descriptor.setReadMethod(readMethod); } catch (Exception e) { log.error("Error setting indexed property read method", e); } } } if (descriptor.getWriteMethod() == null) { String methodName = descriptor.getIndexedWriteMethod() != null ? descriptor.getIndexedWriteMethod().getName() : "set" + propName; Method writeMethod = MethodUtils.getMatchingAccessibleMethod(beanClass, methodName, LIST_CLASS_PARAMETER); if (writeMethod == null) { Method[] methods = beanClass.getMethods(); for (int j = 0; j < methods.length; j++) { if (methods[j].getName().equals(methodName)) { Class[] parameterTypes = methods[j].getParameterTypes(); if (parameterTypes.length == 1 && List.class.isAssignableFrom(parameterTypes[0])) { writeMethod = methods[j]; break; } } } } if (writeMethod != null) { try { descriptor.setWriteMethod(writeMethod); } catch (Exception e) { log.error("Error setting indexed property write method", e); } } } } } // ----------------- Workaround for Bug 28358 ---------- END ------------------- descriptorsCache.put(beanClass, descriptors); return (descriptors); }
From source file:de.hybris.platform.webservices.AbstractWebServicesTest.java
private Map<String, PropertyDescriptor> getPropertyDescriptors(final Class clazz) { final Map<String, PropertyDescriptor> result = new HashMap<String, PropertyDescriptor>(); try {//from w w w . jav a2 s . c o m final PropertyDescriptor[] pdList = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); for (final PropertyDescriptor pd : pdList) { result.put(pd.getName(), pd); } } catch (final Exception e) { LOG.error(e.getMessage(), e); Assert.fail(); } return result; }