List of usage examples for java.beans PropertyDescriptor getReadMethod
public synchronized Method getReadMethod()
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 {/*ww w .j a v a2 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); } }
From source file:net.authorize.api.controller.test.ApiCoreTestBase.java
public static void showProperties(Object bean) { if (null == bean) { return;//w w w . j a va 2s. c o m } try { BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class); PropertyDescriptor[] props = info.getPropertyDescriptors(); for (PropertyDescriptor pd : props) { String name = pd.getName(); Method getter = pd.getReadMethod(); Class<?> type = pd.getPropertyType(); if (null != getter && !"class".equals(name)) { Object value = getter.invoke(bean); logger.info(String.format("Type: '%s', Name:'%s', Value:'%s'", type, name, value)); processCollections(type, name, value); //process compositions of custom classes if (null != value && 0 <= type.toString().indexOf("net.authorize.")) { showProperties(value); } } } } catch (Exception e) { logger.error(String.format("Exception during navigating properties: Message: %s, StackTrace: %s", e.getMessage(), e.getStackTrace())); } }
From source file:org.jaffa.util.BeanHelper.java
/** This will inspect the specified java bean, and extract an Object from the beans * getXxx() method, where 'xxx' is the field name passed in. * A null will be returned in case there is any error in invoking the getter. * @param bean The Java Bean./*from w w w. j a v a 2s.c om*/ * @param field The field. * @throws NoSuchMethodException if there is no getter for the input field. * @return the output of the getter for the field. */ public static Object getField(Object bean, String field) throws NoSuchMethodException { java.lang.reflect.Method method = null; try { if (bean instanceof DynaBean) { try { return PropertyUtils.getProperty(bean, field); } catch (NoSuchMethodException e) { // If the bean is a FlexBean instance, then the field could exist on the associated persistentObject if (bean instanceof FlexBean && ((FlexBean) bean).getPersistentObject() != null) return PropertyUtils.getProperty(((FlexBean) bean).getPersistentObject(), field); else throw e; } } else { // Get the Java Bean Info java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean.getClass()); if (info != null) { // Get all the properties java.beans.PropertyDescriptor[] pds = info.getPropertyDescriptors(); if (pds != null) { // Loop for a matching method for (PropertyDescriptor pd : pds) { if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), field)) { // Match found.... method = pd.getReadMethod(); break; } } } } if (method != null) { return method.invoke(bean, new Object[] {}); } // Finally, check the FlexBean if (bean instanceof IFlexFields) { FlexBean flexBean = ((IFlexFields) bean).getFlexBean(); if (flexBean != null && flexBean.get(field) != null) { return flexBean.get(field); } else { throw new NoSuchMethodException(); } } } } catch (NoSuchMethodException ex) { throw ex; } catch (Exception ex) { log.error("Introspection of Property " + field + " on Bean " + bean + " failed. Reason : " + ex.getMessage(), ex); return null; } // If we reach here, the method was not found throw new NoSuchMethodException("Field Name = " + field); }
From source file:de.hasait.clap.impl.CLAPClassNode.java
private static <T extends Annotation> T getAnnotation(final PropertyDescriptor pPropertyDescriptor, final Class<T> pAnnotationClass) { final Method writeMethod = pPropertyDescriptor.getWriteMethod(); if (writeMethod != null) { final T annotation = writeMethod.getAnnotation(pAnnotationClass); if (annotation != null) { return annotation; }//from w ww.ja v a 2s .c om } final Method readMethod = pPropertyDescriptor.getReadMethod(); if (readMethod != null) { final T annotation = readMethod.getAnnotation(pAnnotationClass); if (annotation != null) { return annotation; } } return null; }
From source file:net.zcarioca.zcommons.config.data.BeanPropertySetterFactory.java
private static Collection<Annotation> getPropertyAnnotations(Field field, PropertyDescriptor descriptor) { Map<Class<? extends Annotation>, Annotation> annotations = new HashMap<Class<? extends Annotation>, Annotation>(); if (descriptor != null) { if (descriptor.getWriteMethod() != null) { addAnnotationsToMap(annotations, descriptor.getWriteMethod().getAnnotations()); }//w w w . j av a 2s . c o m if (descriptor.getReadMethod() != null) { addAnnotationsToMap(annotations, descriptor.getReadMethod().getAnnotations()); } } if (field != null) { addAnnotationsToMap(annotations, field.getAnnotations()); } return annotations.values(); }
From source file:com.wavemaker.json.type.reflect.ReflectTypeUtils.java
/** * Initializes a TypeDefinition from a given class. The first entry in the return list is the TypeDefinition for the * parameter class; any entries after that (if any) are TypeDefinitions for any other types that were required as * fields for that root TypeDefinition./*from w w w .ja v a 2s . c om*/ * * @param klass The Class object to describe. * @param typeState The TypeState for the current operation. * @param strict True indicates that processing should stop on ambiguous entries; false indicates that null should * be entered. * @return A list of TypeDefinitions; the first entry is the root (corresponding with the klass parameter), any * other entries in the list were required to describe the root TypeDefinition's fields. The return may also * be null, if sufficient information was not provided to determine the type. */ public static TypeDefinition getTypeDefinition(Type type, TypeState typeState, boolean strict) { Class<?> klass; // we already know about this type; we're done if (typeState.isTypeKnown(ReflectTypeUtils.getTypeName(type))) { return typeState.getType(ReflectTypeUtils.getTypeName(type)); } // if the type is Object, return null, we can't figure out anything more if (type instanceof Class && Object.class.equals(type)) { return null; } // if we don't have enough information, return null if (!strict) { if (type instanceof Class && Map.class.isAssignableFrom((Class<?>) type) && !Properties.class.isAssignableFrom((Class<?>) type)) { if (!JSON.class.isAssignableFrom((Class<?>) type)) { logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type)); } return null; } else if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) { if (!JSON.class.isAssignableFrom((Class<?>) type)) { logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type)); } return null; } } TypeDefinition ret; if (type instanceof Class && Properties.class.isAssignableFrom((Class<?>) type)) { MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition(); mtdret.setTypeName(ReflectTypeUtils.getTypeName(type)); mtdret.setShortName(ReflectTypeUtils.getShortName(type)); typeState.addType(mtdret); klass = (Class<?>) type; mtdret.setKlass(klass); TypeDefinition stringType = getTypeDefinition(String.class, typeState, false); mtdret.setKeyFieldDefinition(new GenericFieldDefinition(stringType)); mtdret.setValueFieldDefinition(new GenericFieldDefinition(stringType)); ret = mtdret; } else if (type instanceof Class && JSONUtils.isPrimitive((Class<?>) type)) { PrimitiveReflectTypeDefinition ptret; if (((Class<?>) type).isEnum()) { ptret = new EnumPrimitiveReflectTypeDefinition(); } else { ptret = new PrimitiveReflectTypeDefinition(); } ptret.setTypeName(ReflectTypeUtils.getTypeName(type)); ptret.setShortName(ReflectTypeUtils.getShortName(type)); typeState.addType(ptret); klass = (Class<?>) type; ptret.setKlass(klass); ret = ptret; } else if (type instanceof Class) { klass = (Class<?>) type; if (Collection.class.isAssignableFrom(klass)) { throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass); } else if (klass.isArray()) { throw new WMRuntimeException(MessageResource.JSON_USE_FIELD_FOR_ARRAY, klass); } else if (Map.class.isAssignableFrom(klass)) { throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass); } else if (ClassUtils.isPrimitiveOrWrapper(klass) || CharSequence.class.isAssignableFrom(klass)) { PrimitiveReflectTypeDefinition ptret = new PrimitiveReflectTypeDefinition(); ptret.setTypeName(ReflectTypeUtils.getTypeName(type)); ptret.setShortName(ReflectTypeUtils.getShortName(type)); typeState.addType(ptret); ptret.setKlass(klass); ret = ptret; } else { ObjectReflectTypeDefinition otret = new ObjectReflectTypeDefinition(); otret.setTypeName(ReflectTypeUtils.getTypeName(type)); otret.setShortName(ReflectTypeUtils.getShortName(type)); otret.setKlass(klass); typeState.addType(otret); PropertyUtilsBean pub = ((ReflectTypeState) typeState).getPropertyUtilsBean(); PropertyDescriptor[] pds = pub.getPropertyDescriptors(klass); otret.setFields(new LinkedHashMap<String, FieldDefinition>(pds.length)); for (PropertyDescriptor pd : pds) { if (pd.getName().equals("class")) { continue; } Type paramType; if (pd.getReadMethod() != null) { paramType = pd.getReadMethod().getGenericReturnType(); } else if (pd.getWriteMethod() != null) { paramType = pd.getWriteMethod().getGenericParameterTypes()[0]; } else { logger.warn("No getter in type " + pd.getName()); continue; } otret.getFields().put(pd.getName(), getFieldDefinition(paramType, typeState, strict, pd.getName())); } ret = otret; } } else if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; if (pt.getRawType() instanceof Class && Map.class.isAssignableFrom((Class<?>) pt.getRawType())) { MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition(); mtdret.setTypeName(ReflectTypeUtils.getTypeName(type)); mtdret.setShortName(ReflectTypeUtils.getShortName(type)); typeState.addType(mtdret); Type[] types = pt.getActualTypeArguments(); mtdret.setKeyFieldDefinition(getFieldDefinition(types[0], typeState, strict, null)); mtdret.setValueFieldDefinition(getFieldDefinition(types[1], typeState, strict, null)); mtdret.setKlass((Class<?>) pt.getRawType()); ret = mtdret; } else { throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNRAWTYPE, pt.getOwnerType(), pt); } } else { throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNPARAMTYPE, type, type != null ? type.getClass() : null); } return ret; }
From source file:io.uengine.util.ReflectionUtils.java
/** * ?? ? Getter .//from ww w . ja va2 s .c om * * @param instance ? * @param fieldName ? * @return Getter * @throws io.uengine.common.exception.ServiceException Getter */ public static Method getGetterMethod(Object instance, String fieldName) throws ServiceException { try { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(instance, fieldName); return propertyDescriptor.getReadMethod(); } catch (Exception e) { String message = MessageFormatter .format("Cannot find getter method of '{}' in '{}'.", fieldName, instance.getClass().getName()) .getMessage(); throw new ServiceException(message, e); } }
From source file:ch.flashcard.HibernateDetachUtility.java
private static void nullOutFieldsByAccessors(Object value, Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType) throws Exception { // Null out any collections that aren't loaded BeanInfo bi = Introspector.getBeanInfo(value.getClass(), Object.class); PropertyDescriptor[] pds = bi.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { Object propertyValue = null; try {// w ww . jav a 2 s .c o m propertyValue = pd.getReadMethod().invoke(value); } catch (Throwable lie) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't load: " + pd.getName() + " off of " + value.getClass().getSimpleName(), lie); } } if (!Hibernate.isInitialized(propertyValue)) { try { if (LOG.isDebugEnabled()) { LOG.debug("Nulling out: " + pd.getName() + " off of " + value.getClass().getSimpleName()); } Method writeMethod = pd.getWriteMethod(); if ((writeMethod != null) && (writeMethod.getAnnotation(XmlTransient.class) == null)) { pd.getWriteMethod().invoke(value, new Object[] { null }); } else { nullOutField(value, pd.getName()); } } catch (Exception lie) { LOG.debug("Couldn't null out: " + pd.getName() + " off of " + value.getClass().getSimpleName() + " trying field access", lie); nullOutField(value, pd.getName()); } } else { if ((propertyValue instanceof Collection) || ((propertyValue != null) && propertyValue.getClass().getName().startsWith("org.rhq.core.domain"))) { nullOutUninitializedFields(propertyValue, checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); } } } }
From source file:org.eclipse.wb.internal.rcp.databinding.model.beans.bindables.BeanSupport.java
/** * @return <code>true</code> if given {@link PropertyDescriptor} describe property with * <code>getter</code> method and with not primitive and not array type. *//*from w w w .j a va 2 s . co m*/ public static boolean isGetter(PropertyDescriptor descriptor) { // check NPE if (descriptor == null) { return false; } // check type Class<?> type = descriptor.getPropertyType(); // if (type == null || type.isArray() || type.isPrimitive()) { return false; } // check getter method return descriptor.getReadMethod() != null; }
From source file:org.apache.syncope.core.misc.jexl.JexlUtil.java
public static JexlContext addFieldsToContext(final Object object, final JexlContext jexlContext) { JexlContext context = jexlContext == null ? new MapContext() : jexlContext; try {/*w ww.ja v a 2 s . c o m*/ for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) { final Class<?> type = desc.getPropertyType(); final String fieldName = desc.getName(); if ((!fieldName.startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, fieldName)) && (!Iterable.class.isAssignableFrom(type)) && (!type.isArray())) { try { final Method getter = desc.getReadMethod(); final Object fieldValue; if (getter == null) { final Field field = object.getClass().getDeclaredField(fieldName); field.setAccessible(true); fieldValue = field.get(object); } else { fieldValue = getter.invoke(object); } context.set(fieldName, fieldValue == null ? StringUtils.EMPTY : (type.equals(Date.class) ? DataFormat.format((Date) fieldValue, false) : fieldValue)); LOG.debug("Add field {} with value {}", fieldName, fieldValue); } catch (Exception iae) { LOG.error("Reading '{}' value error", fieldName, iae); } } } } catch (IntrospectionException ie) { LOG.error("Reading class attributes error", ie); } return context; }