List of usage examples for java.beans PropertyDescriptor getReadMethod
public synchronized Method getReadMethod()
From source file:es.logongas.ix3.util.ReflectionUtil.java
/** * Este mtodo/* ww w. jav a 2 s. c o m*/ * * @param clazz * @param propertyName El nombre de la propiedad permite que sean varias * "nested" con puntos. Ej: "prop1.prop2.prop3" * @return */ private static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) { try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); if ((propertyName == null) || (propertyName.trim().isEmpty())) { throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio"); } String leftPropertyName; //El nombre de la propiedad antes del primer punto String rigthPropertyName; //El nombre de la propiedad despues del primer punto int indexPoint = propertyName.indexOf("."); if (indexPoint < 0) { leftPropertyName = propertyName; rigthPropertyName = null; } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) { leftPropertyName = propertyName.substring(0, indexPoint); rigthPropertyName = propertyName.substring(indexPoint + 1); } else { throw new RuntimeException("El punto no puede estar ni al principio ni al final"); } PropertyDescriptor propertyDescriptorFind = null; for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals(leftPropertyName)) { propertyDescriptorFind = propertyDescriptor; break; } } if (propertyDescriptorFind == null) { throw new RuntimeException("No existe el propertyDescriptorFind de " + leftPropertyName); } if (rigthPropertyName != null) { Method readMethod = propertyDescriptorFind.getReadMethod(); if (readMethod == null) { throw new RuntimeException("No existe el metodo 'get' de " + leftPropertyName); } Class readClass = readMethod.getReturnType(); return getPropertyDescriptor(readClass, rigthPropertyName); } else { return propertyDescriptorFind; } } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.fengduo.bee.commons.core.lang.CollectionUtils.java
public static <M> void merge(M original, M destination, List<String> ignore) throws Exception { BeanInfo beanInfo = Introspector.getBeanInfo(original.getClass()); // Iterate over all the attributes for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) { // Only copy writable attributes if (descriptor.getWriteMethod() != null) { Object originalValue = descriptor.getReadMethod().invoke(original); String attributeName = descriptor.getName(); // ignore this values,do'not merge if (ignore != null && !ignore.isEmpty() && ignore.contains(attributeName)) { continue; }// www . j av a 2 s . com Object defaultValue = descriptor.getReadMethod().invoke(destination); // Only copy values values where the destination values is null if (originalValue == null) { descriptor.getWriteMethod().invoke(original, defaultValue); } if (defaultValue instanceof Number && originalValue instanceof Number) { descriptor.getWriteMethod().invoke(original, MathUtils.add((Number) originalValue, (Number) defaultValue)); } } } }
From source file:com.sparkplatform.api.core.PropertyAsserter.java
/** * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Only difference is that here we accept an * explicit argument for the setter method. * * @param target the object on which to invoke the getter and setter * @param property the property name, e.g. "firstName" * @param argument the property value, i.e. the value the setter will be invoked with *///from w w w.j a v a 2 s .co m public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) { try { PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass()); Object arg = argument; Class type = descriptor.getPropertyType(); if (arg == null) { if (type.isArray()) { arg = Array.newInstance(type.getComponentType(), new int[] { TEST_ARRAY_SIZE }); } else if (type.isEnum()) { arg = type.getEnumConstants()[0]; } else if (TYPE_ARGUMENTS.containsKey(type)) { arg = TYPE_ARGUMENTS.get(type); } else { arg = invokeDefaultConstructorEvenIfPrivate(type); } } Method writeMethod = descriptor.getWriteMethod(); Method readMethod = descriptor.getReadMethod(); writeMethod.invoke(target, arg); Object propertyValue = readMethod.invoke(target); if (type.isPrimitive()) { assertEquals(property + " getter/setter failed test", arg, propertyValue); } else { assertSame(property + " getter/setter failed test", arg, propertyValue); } } catch (IntrospectionException e) { String msg = "Error creating PropertyDescriptor for property [" + property + "]. Do you have a getter and a setter?"; log.error(msg, e); fail(msg); } catch (IllegalAccessException e) { String msg = "Error accessing property. Are the getter and setter both accessible?"; log.error(msg, e); fail(msg); } catch (InvocationTargetException e) { String msg = "Error invoking method on target"; log.error(msg, e); fail(msg); } }
From source file:grails.util.GrailsClassUtils.java
/** * Checks whether the specified property is inherited from a super class * * @param clz The class to check/* www. j av a 2 s. c o m*/ * @param propertyName The property name * @return true if the property is inherited */ @SuppressWarnings("rawtypes") public static boolean isPropertyInherited(Class clz, String propertyName) { if (clz == null) return false; Assert.isTrue(StringUtils.hasText(propertyName), "Argument [propertyName] cannot be null or blank"); Class<?> superClass = clz.getSuperclass(); PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(superClass, propertyName); if (pd != null && pd.getReadMethod() != null) { return true; } return false; }
From source file:org.apache.syncope.core.provisioning.java.jexl.JexlUtils.java
public static void addFieldsToContext(final Object object, final JexlContext jexlContext) { Set<PropertyDescriptor> cached = FIELD_CACHE.get(object.getClass()); if (cached == null) { cached = new HashSet<>(); FIELD_CACHE.put(object.getClass(), cached); try {/* w ww .j a v a 2s . c om*/ for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass()) .getPropertyDescriptors()) { if ((!desc.getName().startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, desc.getName())) && (!Iterable.class.isAssignableFrom(desc.getPropertyType())) && (!desc.getPropertyType().isArray())) { cached.add(desc); } } } catch (IntrospectionException ie) { LOG.error("Reading class attributes error", ie); } } for (PropertyDescriptor desc : cached) { String fieldName = desc.getName(); Class<?> fieldType = desc.getPropertyType(); try { Object fieldValue; if (desc.getReadMethod() == null) { final Field field = object.getClass().getDeclaredField(fieldName); field.setAccessible(true); fieldValue = field.get(object); } else { fieldValue = desc.getReadMethod().invoke(object); } fieldValue = fieldValue == null ? StringUtils.EMPTY : (fieldType.equals(Date.class) ? FormatUtils.format((Date) fieldValue, false) : fieldValue); jexlContext.set(fieldName, fieldValue); LOG.debug("Add field {} with value {}", fieldName, fieldValue); } catch (Exception iae) { LOG.error("Reading '{}' value error", fieldName, iae); } } if (object instanceof Any && ((Any<?>) object).getRealm() != null) { jexlContext.set("realm", ((Any<?>) object).getRealm().getFullPath()); } else if (object instanceof AnyTO && ((AnyTO) object).getRealm() != null) { jexlContext.set("realm", ((AnyTO) object).getRealm()); } else if (object instanceof Realm) { jexlContext.set("fullPath", ((Realm) object).getFullPath()); } else if (object instanceof RealmTO) { jexlContext.set("fullPath", ((RealmTO) object).getFullPath()); } }
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(); }//from ww w.j ava 2 s.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:com.avanza.ymer.MongoQueryFactory.java
private boolean isNotTemplatableMethod(PropertyDescriptor pd) { return pd.getReadMethod() == null || pd.getReadMethod().getDeclaringClass() == Object.class || pd.getWriteMethod() == null || pd.getName().equals("versionID"); }
From source file:ch.rasc.extclassgenerator.ModelGenerator.java
private static void createModelBean(ModelBean model, AccessibleObject accessibleObject, OutputConfig outputConfig) {//www . j a v a 2 s . co m Class<?> javaType = null; String name = null; Class<?> declaringClass = null; if (accessibleObject instanceof Field) { Field field = (Field) accessibleObject; javaType = field.getType(); name = field.getName(); declaringClass = field.getDeclaringClass(); } else if (accessibleObject instanceof Method) { Method method = (Method) accessibleObject; javaType = method.getReturnType(); if (javaType.equals(Void.TYPE)) { return; } if (method.getName().startsWith("get")) { name = StringUtils.uncapitalize(method.getName().substring(3)); } else if (method.getName().startsWith("is")) { name = StringUtils.uncapitalize(method.getName().substring(2)); } else { name = method.getName(); } declaringClass = method.getDeclaringClass(); } ModelType modelType = null; if (model.isAutodetectTypes()) { for (ModelType mt : ModelType.values()) { if (mt.supports(javaType)) { modelType = mt; break; } } } else { modelType = ModelType.AUTO; } ModelFieldBean modelFieldBean = null; ModelField modelFieldAnnotation = accessibleObject.getAnnotation(ModelField.class); if (modelFieldAnnotation != null) { if (StringUtils.hasText(modelFieldAnnotation.value())) { name = modelFieldAnnotation.value(); } if (StringUtils.hasText(modelFieldAnnotation.customType())) { modelFieldBean = new ModelFieldBean(name, modelFieldAnnotation.customType()); } else { ModelType type = null; if (modelFieldAnnotation.type() != ModelType.NOT_SPECIFIED) { type = modelFieldAnnotation.type(); } else { type = modelType; } modelFieldBean = new ModelFieldBean(name, type); } updateModelFieldBean(modelFieldBean, modelFieldAnnotation); model.addField(modelFieldBean); } else { if (modelType != null) { modelFieldBean = new ModelFieldBean(name, modelType); model.addField(modelFieldBean); } } ModelId modelIdAnnotation = accessibleObject.getAnnotation(ModelId.class); if (modelIdAnnotation != null) { model.setIdProperty(name); } ModelClientId modelClientId = accessibleObject.getAnnotation(ModelClientId.class); if (modelClientId != null) { model.setClientIdProperty(name); model.setClientIdPropertyAddToWriter(modelClientId.configureWriter()); } ModelVersion modelVersion = accessibleObject.getAnnotation(ModelVersion.class); if (modelVersion != null) { model.setVersionProperty(name); } ModelAssociation modelAssociationAnnotation = accessibleObject.getAnnotation(ModelAssociation.class); if (modelAssociationAnnotation != null) { model.addAssociation(AbstractAssociation.createAssociation(modelAssociationAnnotation, model, javaType, declaringClass, name)); } if (modelFieldBean != null && outputConfig.getIncludeValidation() != IncludeValidation.NONE) { Set<ModelValidation> modelValidationAnnotations = AnnotationUtils .getRepeatableAnnotation(accessibleObject, ModelValidations.class, ModelValidation.class); if (!modelValidationAnnotations.isEmpty()) { for (ModelValidation modelValidationAnnotation : modelValidationAnnotations) { AbstractValidation modelValidation = AbstractValidation.createValidation(name, modelValidationAnnotation, outputConfig.getIncludeValidation()); if (modelValidation != null) { model.addValidation(modelValidation); } } } else { Annotation[] fieldAnnotations = accessibleObject.getAnnotations(); for (Annotation fieldAnnotation : fieldAnnotations) { AbstractValidation.addValidationToModel(model, modelFieldBean, fieldAnnotation, outputConfig.getIncludeValidation()); } if (accessibleObject instanceof Field) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(declaringClass, name); if (pd != null && pd.getReadMethod() != null) { for (Annotation readMethodAnnotation : pd.getReadMethod().getAnnotations()) { AbstractValidation.addValidationToModel(model, modelFieldBean, readMethodAnnotation, outputConfig.getIncludeValidation()); } } } } } }
From source file:com.emc.ecs.sync.config.ConfigPropertyWrapper.java
public ConfigPropertyWrapper(PropertyDescriptor descriptor) { if (!descriptor.getReadMethod().isAnnotationPresent(Option.class)) throw new IllegalArgumentException(descriptor.getName() + " is not an @Option"); this.descriptor = descriptor; this.option = descriptor.getReadMethod().getAnnotation(Option.class); this.locations = new HashSet<>(Arrays.asList(this.option.locations())); this.cliOption = ConfigUtil.cliOptionFromAnnotation(descriptor, getAnnotation(), null); }
From source file:org.codehaus.groovy.grails.orm.hibernate.support.HibernateBeanWrapper.java
/** * Checks Hibernate.isInitialized before calling super method. * * @param name target property/* w w w. j a v a 2s . c om*/ * @return null if false or super'name value if true * @throws BeansException */ @Override public Object getPropertyValue(String name) throws BeansException { PropertyDescriptor desc = getPropertyDescriptor(name); Method method = desc.getReadMethod(); Object owner = getWrappedInstance(); try { if (Hibernate.isInitialized(method.invoke(owner))) { return super.getPropertyValue(name); } } catch (Exception e) { log.error("Error checking Hibernate initialization on method " + method.getName() + " for class " + owner.getClass().getName(), e); } return null; }