List of usage examples for java.beans PropertyDescriptor getName
public String getName()
From source file:net.mojodna.sprout.support.SproutUtils.java
/** * Bean initialization method. Uses reflection to determine properties * for which auto-wiring may be appropriate. Subsequently attempts to * retrieve appropriate beans from the WebApplicationContext and set them * locally./*from w ww. j a v a 2s.c om*/ * * @param bean Bean to initialize. * @param context WebApplicationContext containing Spring beans. * @param clazz Type of Sprout. This is used to determine which declared * methods are candidates for auto-wiring. */ public static void initialize(final Object bean, final WebApplicationContext context, final Class clazz) { final Collection<Method> methods = SproutUtils.getDeclaredMethods(bean.getClass(), clazz); final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(bean.getClass()); for (final PropertyDescriptor descriptor : descriptors) { final Class type = descriptor.getPropertyType(); // beans should never be of type String // there must be a write method present // the write method must exist within the relevant subset of declared methods if (!type.equals(String.class) && null != descriptor.getWriteMethod() && methods.contains(descriptor.getWriteMethod())) { final Object serviceBean = context.getBean(descriptor.getName()); if (null != serviceBean) { try { log.debug("Wiring property '" + descriptor.getName() + "' with bean of type " + serviceBean.getClass().getName()); PropertyUtils.setProperty(bean, descriptor.getName(), serviceBean); } catch (final IllegalAccessException e) { throw new RuntimeException(e); } catch (final InvocationTargetException e) { throw new RuntimeException(e); } catch (final NoSuchMethodException e) { throw new RuntimeException(e); } } } } /** * TODO additional lifecycle interface callbacks as defined in BeanFactory * should be implemented here * @see org.springframework.beans.factory.BeanFactory */ // InitializingBean callback if (bean instanceof InitializingBean) { try { ((InitializingBean) bean).afterPropertiesSet(); } catch (final Exception e) { log.warn("Exception while running afterPropertiesSet() on an InitializingBean: " + e.getMessage(), e); } } }
From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java
/** * ?/*from w w w . ja v a 2 s .c om*/ * * @param method * @return */ public static Object buildTypeStructure(Class<?> type, Type genericType, Type oriGenericType) { if ("void".equalsIgnoreCase(type.getName()) || ClassUtils.isPrimitiveOrWrapper(type) || String.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type) || URL.class.isAssignableFrom(type)) { // return type.getName().replaceAll("java.lang.", "").replaceAll("java.util.", "").replaceAll("java.sql.", ""); } // end if if (type.isArray()) { // return new Object[] { buildTypeStructure(type.getComponentType(), type.getComponentType(), genericType) }; } // end if if (ClassUtils.isAssignable(Map.class, type)) { // Map return Map.class.getName(); } // end if if (type.isEnum()) { // Enum return Enum.class.getName(); } // end if boolean isCollection = type != null ? Collection.class.isAssignableFrom(type) : false; if (isCollection) { Type rawType = type; if (genericType != null) { if (genericType instanceof ParameterizedType) { ParameterizedType _type = (ParameterizedType) genericType; Type[] actualTypeArguments = _type.getActualTypeArguments(); rawType = actualTypeArguments[0]; } else if (genericType instanceof GenericArrayType) { rawType = ((GenericArrayType) genericType).getGenericComponentType(); } if (genericType instanceof WildcardType) { rawType = ((WildcardType) genericType).getUpperBounds()[0]; } } if (rawType == type) { return new Object[] { rawType.getClass().getName() }; } else { if (rawType.getClass().isAssignableFrom(TypeVariableImpl.class)) { return new Object[] { buildTypeStructure( (Class<?>) ((ParameterizedType) oriGenericType).getActualTypeArguments()[0], rawType, genericType) }; } else { if (rawType instanceof ParameterizedType) { if (((ParameterizedType) rawType).getRawType() == Map.class) { return new Object[] { Map.class.getName() }; } } if (oriGenericType == rawType) { return new Object[] { rawType.getClass().getName() }; } return new Object[] { buildTypeStructure((Class<?>) rawType, rawType, genericType) }; } } } if (type.isInterface()) { return type.getName(); } ClassInfo paramClassInfo = RPCAPIDocletUtil.getClassInfo(type.getName()); //added if (null == paramClassInfo) { System.out.println("failed to get paramClassInfo for :" + type.getName()); return null; } List<FieldInfo> typeConstructure = new ArrayList<FieldInfo>(); BeanWrapper bean = new BeanWrapperImpl(type); PropertyDescriptor[] propertyDescriptors = bean.getPropertyDescriptors(); Method readMethod; String name; for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { readMethod = propertyDescriptor.getReadMethod(); if (readMethod == null || "getClass".equals(readMethod.getName())) { continue; } name = propertyDescriptor.getName(); FieldInfo fieldInfo = paramClassInfo.getFieldInfo(name); if (readMethod.getReturnType().isAssignableFrom(type)) { String comment = "structure is the same with parent."; typeConstructure .add(FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", comment)); } else { typeConstructure.add( FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", buildTypeStructure( readMethod.getReturnType(), readMethod.getGenericReturnType(), genericType))); } // end if } return typeConstructure; }
From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java
public static Class<?> getPropertyType(Class<?> type, String propertyName) { String[] propertyTokens = StringUtils.split(propertyName, "."); Class<?> result = type; for (String propertyToken : propertyTokens) { PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(result); for (PropertyDescriptor descriptor : descriptors) { if (StringUtils.equalsIgnoreCase(propertyToken, descriptor.getName())) { result = descriptor.getPropertyType(); break; } else { result = null;// w ww . j a v a2 s . c o m } } } return result; }
From source file:net.authorize.api.controller.test.ApiCoreTestBase.java
public static void showProperties(Object bean) { if (null == bean) { return;/*ww w . j ava2s . c om*/ } 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:com.bstek.dorado.idesupport.template.RuleTemplate.java
private static void applyProperties(Object source, Object target) throws Exception { for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(target)) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { applyProperty(source, target, propertyDescriptor.getName()); }//from ww w . j av a2s . c o m } }
From source file:com.twinsoft.convertigo.beans.CheckBeans.java
private static void analyzeJavaClass(String javaClassName) { try {// ww w . j a va2 s.c o m Class<?> javaClass = Class.forName(javaClassName); String javaClassSimpleName = javaClass.getSimpleName(); if (!DatabaseObject.class.isAssignableFrom(javaClass)) { //Error.NON_DATABASE_OBJECT.add(javaClassName); return; } nBeanClass++; String dboBeanInfoClassName = javaClassName + "BeanInfo"; MySimpleBeanInfo dboBeanInfo = null; try { dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance(); } catch (ClassNotFoundException e) { if (!Modifier.isAbstract(javaClass.getModifiers())) { Error.MISSING_BEAN_INFO .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")"); } return; } catch (Exception e) { e.printStackTrace(); return; } BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor(); // Check abstract class if (Modifier.isAbstract(javaClass.getModifiers())) { // Check icon (16x16) String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_16x16); if (declaredIconName != null) { Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName); } // Check icon (32x32) declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32); if (declaredIconName != null) { Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName); } // Check display name if (!beanDescriptor.getDisplayName().equals("?")) { Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName); } // Check description if (!beanDescriptor.getShortDescription().equals("?")) { Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName); } } else { nBeanClassNotAbstract++; // Check bean declaration in database_objects.xml if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) { Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName); } // Check icon name policy (16x16) String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_16x16); String expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName); expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16"; expectedIconName = expectedIconName.toLowerCase() + ".png"; if (declaredIconName != null) { if (!declaredIconName.equals(expectedIconName)) { Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + " Declared: " + declaredIconName + "\n" + " Expected: " + expectedIconName); } } // Check icon file (16x16) File iconFile = new File(srcBase + declaredIconName); if (!iconFile.exists()) { Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName); } else { icons.remove(declaredIconName); } // Check icon name policy (32x32) declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32); expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName); expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32"; expectedIconName = expectedIconName.toLowerCase() + ".png"; if (declaredIconName != null) { if (!declaredIconName.equals(expectedIconName)) { Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + " Declared: " + declaredIconName + "\n" + " Expected: " + expectedIconName); } } // Check icon file (32x32) iconFile = new File(srcBase + declaredIconName); if (!iconFile.exists()) { Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName); } else { icons.remove(declaredIconName); } // Check display name if (beanDescriptor.getDisplayName().equals("?")) { Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName); } // Check description if (beanDescriptor.getShortDescription().equals("?")) { Error.BEAN_MISSING_DESCRIPTION.add(javaClassName); } } // Check declared bean properties PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); try { javaClass.getDeclaredField(propertyName); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { try { // Try to find it in the upper classes javaClass.getField(propertyName); } catch (SecurityException e1) { // printStackTrace(); } catch (NoSuchFieldException e1) { Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName); } } } Method[] methods = javaClass.getDeclaredMethods(); List<Method> listMethods = Arrays.asList(methods); List<String> listMethodNames = new ArrayList<String>(); for (Method method : listMethods) { listMethodNames.add(method.getName()); } Field[] fields = javaClass.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); // Ignore static fields (constants) if (Modifier.isStatic(fieldModifiers)) continue; String fieldName = field.getName(); String errorMessage = javaClassName + ": " + field.getName(); // Check bean info PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo); if (propertyDescriptor != null) { // Check bean property name policy if (!propertyDescriptor.getName().equals(fieldName)) { Error.PROPERTY_NAMING_POLICY.add(errorMessage); } String declaredGetter = propertyDescriptor.getReadMethod().getName(); String declaredSetter = propertyDescriptor.getWriteMethod().getName(); String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); String expectedGetter = "get" + formattedFieldName; String expectedSetter = "set" + formattedFieldName; // Check getter name policy if (!declaredGetter.equals(expectedGetter)) { Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH .add(errorMessage + "\n" + " Declared getter: " + declaredGetter + "\n" + " Expected getter: " + expectedGetter); } // Check setter name policy if (!declaredSetter.equals(expectedSetter)) { Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH .add(errorMessage + "\n" + " Declared setter: " + declaredSetter + "\n" + " Expected setter: " + expectedSetter); } // Check required private modifiers for bean property if (!Modifier.isPrivate(fieldModifiers)) { Error.PROPERTY_NOT_PRIVATE.add(errorMessage); } // Check getter if (!listMethodNames.contains(declaredGetter)) { Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND .add(errorMessage + " - Declared getter not found: " + declaredGetter); } // Check setter if (!listMethodNames.contains(declaredSetter)) { Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND .add(errorMessage + " - Declared setter not found: " + declaredGetter); } // Check non transient modifier if (Modifier.isTransient(fieldModifiers)) { Error.PROPERTY_TRANSIENT.add(errorMessage); } } else if (!Modifier.isTransient(fieldModifiers)) { Error.FIELD_NOT_TRANSIENT.add(errorMessage); } } } catch (ClassNotFoundException e) { System.out.println("ERROR on " + javaClassName); e.printStackTrace(); } }
From source file:io.coala.enterprise.Fact.java
/** * override and deserialize bean properties as declared in factType * <p>//from w ww .j a va 2 s . co m * TODO detect properties from builder methods: {@code withKey(T value)} * * @param om * @param json * @param factType * @param properties * @return the properties again, to allow chaining * @throws IntrospectionException */ static <T extends Fact> Map<String, Object> fromJSON(final ObjectMapper om, final TreeNode json, final Class<T> factType, final Map<String, Object> properties) { try { final ObjectNode tree = (ObjectNode) json; final BeanInfo beanInfo = Introspector.getBeanInfo(factType); for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) if (tree.has(pd.getName())) properties.computeIfPresent(pd.getName(), (property, current) -> JsonUtil.valueOf(om, tree.get(property), pd.getPropertyType())); return properties; } catch (final Throwable e) { return Thrower.rethrowUnchecked(e); } }
From source file:de.escalon.hypermedia.spring.uber.UberUtils.java
/** * Recursively converts object to nodes of uber data. * * @param objectNode/* w w w .ja v a 2 s . com*/ * to append to * @param object * to convert */ public static void toUberData(AbstractUberNode objectNode, Object object) { Set<String> filtered = FILTER_RESOURCE_SUPPORT; if (object == null) { return; } try { // TODO: move all returns to else branch of property descriptor handling if (object instanceof Resource) { Resource<?> resource = (Resource<?>) object; objectNode.addLinks(resource.getLinks()); toUberData(objectNode, resource.getContent()); return; } else if (object instanceof Resources) { Resources<?> resources = (Resources<?>) object; // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar objectNode.addLinks(resources.getLinks()); Collection<?> content = resources.getContent(); toUberData(objectNode, content); return; } else if (object instanceof ResourceSupport) { ResourceSupport resource = (ResourceSupport) object; objectNode.addLinks(resource.getLinks()); // wrap object attributes below to avoid endless loop } else if (object instanceof Collection) { Collection<?> collection = (Collection<?>) object; for (Object item : collection) { // TODO name must be repeated for each collection item UberNode itemNode = new UberNode(); objectNode.addData(itemNode); toUberData(itemNode, item); } return; } if (object instanceof Map) { Map<?, ?> map = (Map<?, ?>) object; for (Entry<?, ?> entry : map.entrySet()) { String key = entry.getKey().toString(); Object content = entry.getValue(); Object value = getContentAsScalarValue(content); UberNode entryNode = new UberNode(); objectNode.addData(entryNode); entryNode.setName(key); if (value != null) { entryNode.setValue(value); } else { toUberData(entryNode, content); } } } else { Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(object); for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) { String name = propertyDescriptor.getName(); if (filtered.contains(name)) { continue; } UberNode propertyNode = new UberNode(); Object content = propertyDescriptor.getReadMethod().invoke(object); if (isEmptyCollectionOrMap(content, propertyDescriptor.getPropertyType())) { continue; } Object value = getContentAsScalarValue(content); propertyNode.setName(name); objectNode.addData(propertyNode); if (value != null) { // for each scalar property of a simple bean, add valuepair nodes to data propertyNode.setValue(value); } else { toUberData(propertyNode, content); } } Field[] fields = object.getClass().getFields(); for (Field field : fields) { String name = field.getName(); if (!propertyDescriptors.containsKey(name)) { Object content = field.get(object); Class<?> type = field.getType(); if (isEmptyCollectionOrMap(content, type)) { continue; } UberNode propertyNode = new UberNode(); Object value = getContentAsScalarValue(content); propertyNode.setName(name); objectNode.addData(propertyNode); if (value != null) { // for each scalar property of a simple bean, add valuepair nodes to data propertyNode.setValue(value); } else { toUberData(propertyNode, content); } } } } } catch (Exception ex) { throw new RuntimeException("failed to transform object " + object, ex); } }
From source file:com.github.dozermapper.core.util.ReflectionUtils.java
/** * There are some nasty bugs for introspection with generics. This method addresses those nasty bugs and tries to find proper methods if available * http://bugs.sun.com/view_bug.do?bug_id=6788525 * http://bugs.sun.com/view_bug.do?bug_id=6528714 * * @param clazz type to work on//from w ww . ja v a 2 s .co m * @param descriptor property pair (get/set) information * @return descriptor */ private static PropertyDescriptor fixGenericDescriptor(Class<?> clazz, PropertyDescriptor descriptor) { Method readMethod = descriptor.getReadMethod(); if (readMethod != null && (readMethod.isBridge() || readMethod.isSynthetic())) { String propertyName = descriptor.getName(); //capitalize the first letter of the string; String baseName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); String setMethodName = "set" + baseName; String getMethodName = "get" + baseName; Method getMethod = findPreferablyNonSyntheticMethod(getMethodName, clazz); Method setMethod = findPreferablyNonSyntheticMethod(setMethodName, clazz); try { return new PropertyDescriptor(propertyName, getMethod, setMethod); } catch (IntrospectionException e) { //move on } } return descriptor; }
From source file:net.mojodna.searchable.util.SearchableUtils.java
/** * @param clazz/*w w w .ja v a 2 s . c o m*/ * @return Fields. */ public static final Field[] getFields(final Class<? extends Searchable> clazz) { Set<Field> fields = new HashSet<Field>(); for (final PropertyDescriptor d : PropertyUtils.getPropertyDescriptors(clazz)) { if (containsIndexAnnotations(d)) { final Field.Store stored = isStored(d); final Field.Index indexStyle = getIndexStyle(d); final float boost = getBoost(d); for (final String name : getFieldnames(d)) { final Field f = new Field(name, clazz.getName() + "#" + d.getName(), stored, indexStyle); f.setBoost(boost); fields.add(f); } } if (containsSortableAnnotations(d)) { fields.add(new Field(IndexSupport.SORTABLE_PREFIX + d.getName(), clazz.getName(), Field.Store.YES, Field.Index.NO)); } } return fields.toArray(new Field[] {}); }