@Override public List<T> handle(ResultSet rs) throws SQLException { List<T> list = new LinkedList<>(); while (rs.next()) { try { T t = this.clz.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(this.clz, Object.class); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); Map<String, Object> map = new HashMap<String, Object>(); for (PropertyDescriptor pd : descriptors) { String propertyName = pd.getName(); Class<?> propertyType = pd.getPropertyType(); if (propertyType.isAnnotationPresent(Entry.class)) { propertyName = propertyName + "_id"; } Object value = rs.getObject(propertyName); if (propertyType.isAnnotationPresent(Entry.class)) { value = getObject(value, propertyType); } map.put(pd.getName(), value); } BeanUtils.copyProperties(t, map); list.add(t); } catch (InstantiationException | IllegalAccessException | IntrospectionException | InvocationTargetException e) { e.printStackTrace(); } } return list; }
/** * @see * org.kuali.kfs.module.cam.document.service.AssetPaymentService#adjustPaymentAmounts(org.kuali.kfs.module.cam.businessobject.AssetPayment, * boolean, boolean) */ public void adjustPaymentAmounts( AssetPayment assetPayment, boolean reverseAmount, boolean nullPeriodDepreciation) throws IllegalAccessException, InvocationTargetException { LOG.debug("Starting - adjustAmounts() "); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(AssetPayment.class); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { KualiDecimal amount = (KualiDecimal) readMethod.invoke(assetPayment); Method writeMethod = propertyDescriptor.getWriteMethod(); if (writeMethod != null && amount != null) { // Reset periodic depreciation expenses if (nullPeriodDepreciation && Pattern.matches( CamsConstants.SET_PERIOD_DEPRECIATION_AMOUNT_REGEX, writeMethod.getName().toLowerCase())) { Object[] nullVal = new Object[] {null}; writeMethod.invoke(assetPayment, nullVal); } else if (reverseAmount) { // reverse the amounts writeMethod.invoke(assetPayment, (amount.negated())); } } } } LOG.debug("Finished - adjustAmounts()"); }
private static void copyCollection( Object target, String[] effectiveProperties, String[] ignoreProperties, Boolean nullBeCopied, PropertyDescriptor targetPd, Object sourceValue, Method writeMethod) throws IllegalAccessException, InvocationTargetException, UtilException, ClassNotFoundException, InstantiationException, NoSuchFieldException { Method targetReadMethod = targetPd.getReadMethod(); Collection targetValue = (Collection) targetReadMethod.invoke(target, null); List tempList = new ArrayList(); if (sourceValue == null) { writeMethod.invoke(target, sourceValue); return; } if (targetValue == null) { if (Set.class.isAssignableFrom(targetPd.getPropertyType())) { targetValue = new HashSet(); } else if (List.class.isAssignableFrom(targetPd.getPropertyType())) { targetValue = new ArrayList(); } else { return; } } Object[] sourceArray = ((Collection) sourceValue).toArray(); Object[] targetArray = targetValue.toArray(); for (int i = 0; i < sourceArray.length; i++) { if (targetValue.contains(sourceArray[i])) { for (int j = 0; j < targetArray.length; j++) { if (sourceArray[i].equals(targetArray[j])) { copyProperties( sourceArray[i], targetArray[j], effectiveProperties, ignoreProperties, nullBeCopied); tempList.add(targetArray[j]); break; } } } else { Object tempTarget = Class.forName(sourceArray[i].getClass().getName()).newInstance(); // 基本类型直接赋值 if (sourceArray[i].getClass().isPrimitive() || sourceArray[i] instanceof String) { tempTarget = sourceArray[i]; } else { copyProperties( sourceArray[i], tempTarget, effectiveProperties, ignoreProperties, nullBeCopied); } tempList.add(tempTarget); } } targetValue.clear(); targetValue.addAll(tempList); return; }
private static Class resolveType(PropertyDescriptor d) { if (TypeResolver.isIntegerType(d.getPropertyType())) { return Integer.class; } else if (TypeResolver.isLongType(d.getPropertyType())) { return Long.class; } else if (TypeResolver.isBooleanType(d.getPropertyType())) { return Boolean.class; } else { return d.getPropertyType(); } }
/** * Create a new CachedIntrospectionResults instance for the given class. * * @param beanClass the bean class to analyze * @throws BeansException in case of introspection failure */ private CachedIntrospectionResults(Class beanClass) throws BeansException { try { if (logger.isTraceEnabled()) { logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]"); } this.beanInfo = Introspector.getBeanInfo(beanClass); // 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 HashMap(); // This call is slow so we do it once. PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; 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 (JdkVersion.isAtLeastJava15()) { pd = new GenericTypeAwarePropertyDescriptor( beanClass, pd.getName(), pd.getReadMethod(), pd.getWriteMethod(), pd.getPropertyEditorClass()); } this.propertyDescriptorCache.put(pd.getName(), pd); } } catch (IntrospectionException ex) { throw new FatalBeanException( "Cannot get BeanInfo for object of class [" + beanClass.getName() + "]", ex); } }
private Class<? extends Object> getPropertyTypeWithClass( Class<? extends Object> clazz, String dataName) throws Exception { if (clazz == null) throw new IllegalArgumentException(); int delim = dataName.indexOf('.'); if (delim < 0) { PropertyDescriptor pd = OgnlRuntime.getPropertyDescriptor(clazz, dataName); if (pd == null) throw new IllegalArgumentException(); return pd.getPropertyType(); } else { PropertyDescriptor pd = OgnlRuntime.getPropertyDescriptor(clazz, dataName.substring(0, delim)); if (pd == null) throw new IllegalArgumentException(); return getPropertyTypeWithClass(pd.getPropertyType(), dataName.substring(delim + 1)); } }
/** * This is a 'smart' (perform checks for some special cases) update function which should be used * to copy of the properties for objects of the catalog and configuration. * * @param <T> the type of the bean to update * @param info the bean instance to update * @param properties the list of string of properties to update * @param values the list of new values to update * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ public static <T> void smartUpdate( final T info, final List<String> properties, final List<Object> values) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Iterator<String> itPropertyName = properties.iterator(); final Iterator<Object> itValue = values.iterator(); while (itPropertyName.hasNext() && itValue.hasNext()) { String propertyName = itPropertyName.next(); final Object value = itValue.next(); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(info, propertyName); // return null if there is no such descriptor if (pd == null) { // this is a special case used by the NamespaceInfoImpl setURI // the propertyName coming from the ModificationProxy is set to 'uRI' // lets set it to uri propertyName = propertyName.toUpperCase(); pd = PropertyUtils.getPropertyDescriptor(info, propertyName); if (pd == null) { return; } } if (pd.getWriteMethod() != null) { PropertyUtils.setProperty(info, propertyName, value); } else { // T interface do not declare setter method for this property // lets use getter methods to get the property reference final Object property = PropertyUtils.getProperty(info, propertyName); // check type of property to apply new value if (Collection.class.isAssignableFrom(pd.getPropertyType())) { final Collection<?> liveCollection = (Collection<?>) property; liveCollection.clear(); liveCollection.addAll((Collection) value); } else if (Map.class.isAssignableFrom(pd.getPropertyType())) { final Map<?, ?> liveMap = (Map<?, ?>) property; liveMap.clear(); liveMap.putAll((Map) value); } else { if (CatalogUtils.LOGGER.isLoggable(java.util.logging.Level.SEVERE)) CatalogUtils.LOGGER.severe( "Skipping unwritable property " + propertyName + " with property type " + pd.getPropertyType()); } } } }
public Optional<String> beanValue(String pattern) { if (fieldvalue.isPresent()) return fieldvalue; try { if (bean == null) return Optional.absent(); Object o = PropertyUtils.getProperty(bean, this.fieldname); PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, this.fieldname); Class c = pd.getPropertyType(); if (c == String.class) { } else if (c == Integer.class || c == int.class) { } else if (c == Long.class || c == long.class) { } else if (c == Float.class || c == float.class) { } else if (c == Boolean.class || c == boolean.class) { } else if (c == Date.class) { } else if (Enum.class.isAssignableFrom(c)) { } return Optional.of((String) o); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } catch (NoSuchMethodException e) { } return Optional.absent(); }
public TypeWrapper(Class c) throws IntrospectionException { Map<String, Field> fields = new HashMap(); loadFields(c, fields); BeanInfo bi = Introspector.getBeanInfo(c, Object.class); PropertyDescriptor[] props = bi.getPropertyDescriptors(); for (int i = 0; i < props.length; i++) { PropertyDescriptor pd = props[i]; Annotation[] ann = null; Field f = fields.get(pd.getName()); if (f != null) { f.getAnnotations(); } Class type = pd.getPropertyType(); boolean arrayFlag = type.isArray(); PropertyInfo pi = new PropertyInfo( pd.getName(), ann, (arrayFlag ? type.getComponentType() : type), arrayFlag, pd.getReadMethod(), pd.getWriteMethod()); this.properties.put(pi.getName(), pi); } }
public static void mapping(Object object, Map<String, ? extends Object> parameter) throws IllegalAccessException, InvocationTargetException { PropertyDescriptor[] pds = getDescriptors(object.getClass()); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; Object obj = parameter.get(pd.getName()); Object value = obj; Class<?> cls = pd.getPropertyType(); if (obj instanceof String) { String string = (String) obj; if (!StringUtil.isEmpty(string)) { string = ConfigUtil.filter(string); } if (isPrimitiveType(cls)) { value = convert(cls, string); } } else if (obj instanceof BeanConfig) { value = createBean((BeanConfig) obj); } else if (obj instanceof BeanConfig[]) { List<Object> list = new ArrayList<Object>(); for (BeanConfig beanconfig : (BeanConfig[]) obj) { list.add(createBean(beanconfig)); } value = list.toArray(); } if (cls != null) { if (value != null) { Method method = pd.getWriteMethod(); if (method != null) { method.invoke(object, new Object[] {value}); } } } } }
/** * 将bean装换为一个map(能将枚举转换为int) * * @param bean * @return */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Map buildMap(Object bean) { if (bean == null) { return null; } try { Map map = describe(bean); PropertyDescriptor[] pds = BEANUTILSBEAN.getPropertyUtils().getPropertyDescriptors(bean); for (PropertyDescriptor pd : pds) { Class type = pd.getPropertyType(); if (type.isEnum()) { Object value = BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, pd.getName()); Enum enums = EnumUtils.valueOf(type, String.valueOf(value)); map.put(pd.getName(), enums == null ? -1 : enums.ordinal()); } else if (type == java.util.Date.class) { // 防止是Timestamp Object value = BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, pd.getName()); if (value != null) { Calendar cal = Calendar.getInstance(); cal.setTime((java.util.Date) value); map.put(pd.getName(), cal.getTime()); } } } return map; } catch (Throwable e) { LOGGER.error("BeanUtil 创建Map失败:", e); throw new RuntimeException(e); } }
/** * Creates a new object and initializes its fields from the ResultSet. * * @param rs The result set. * @param type The bean type (the return type of the object). * @param props The property descriptors. * @param columnToProperty The column indices in the result set. * @return An initialized object. * @throws java.sql.SQLException if a database error occurs. */ private Object createBean( ResultSet rs, Class type, PropertyDescriptor[] props, int[] columnToProperty) throws SQLException { Object bean = this.newInstance(type); for (int i = 1; i < columnToProperty.length; i++) { if (columnToProperty[i] == PROPERTY_NOT_FOUND) { continue; } PropertyDescriptor prop = props[columnToProperty[i]]; Class propType = prop.getPropertyType(); Object value = this.processColumn(rs, i, propType); if (propType != null && value == null && propType.isPrimitive()) { value = primitiveDefaults.get(propType); } this.callSetter(bean, prop, value); } return bean; }
public List gleanAutowiringRequirements( Map compositionContext, PlexusContainer container, ClassRealm componentRealm) { PropertyDescriptor[] propertyDescriptors = (PropertyDescriptor[]) compositionContext.get(PROPERTY_DESCRIPTORS); List requirements = new ArrayList(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor pd = propertyDescriptors[i]; String role = pd.getPropertyType().getName(); ComponentDescriptor componentDescriptor = container.getComponentDescriptor(role, componentRealm); if (componentDescriptor != null) { ComponentRequirement requirement = new ComponentRequirement(); requirement.setRole(role); requirements.add(requirement); } } return requirements; }
private PropertyDescriptor findExistingPropertyDescriptor( String propertyName, Class<?> propertyType) { for (PropertyDescriptor pd : this.propertyDescriptors) { final Class<?> candidateType; final String candidateName = pd.getName(); if (pd instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd; candidateType = ipd.getIndexedPropertyType(); if (candidateName.equals(propertyName) && (candidateType.equals(propertyType) || candidateType.equals(propertyType.getComponentType()))) { return pd; } } else { candidateType = pd.getPropertyType(); if (candidateName.equals(propertyName) && (candidateType.equals(propertyType) || propertyType.equals(candidateType.getComponentType()))) { return pd; } } } return null; }
/** * setArgStringValue purpose. * * <p>Stores a human friendly version. * * @param name * @param value * @return */ public boolean addArgStringValue(String name, String value) { PropertyDescriptor pd = getPropertyDescriptor(name); if (pd == null) { return false; } if ((value == null) || value.equals("")) { args.remove(name); return false; } Class cl = pd.getPropertyType(); ArgumentConfig ac = new ArgumentConfig(); ac.setName(name); try { String argType = ArgHelper.getArgumentType(cl); ac.setValue(ArgHelper.getArgumentInstance(argType, value)); } catch (ValidationException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } args.put(name, ac); return true; }
/** * Perform one setter operation with the provided value. * * @param instance Instance of class under test to operate on. * @param property Property being tested * @param field Field being tested * @param testVal Test value to use. * @return Optional that will contain an error message if the test failed, otherwise empty. * @throws InvocationTargetException * @throws IllegalAccessException */ private Optional<String> testSetterWithVal( T instance, PropertyDescriptor property, Field field, Object testVal) throws InvocationTargetException, IllegalAccessException { Objects.requireNonNull(instance, "Instance of target class required."); boolean status = true; property.getWriteMethod().invoke(instance, testVal); Object expected, actual; if (property.getPropertyType().isPrimitive()) { expected = String.valueOf(testVal); actual = String.valueOf(field.get(instance)); status = expected.equals(actual); } else { expected = testVal; actual = field.get(instance); if (expected == null) { status = actual == null; } else { status = expected.equals(actual); } } if (status == false) { return Optional.of( String.format( "Failed during setter test: %s. Expected: %s Actual: %s", property.getWriteMethod(), expected, actual)); } return Optional.empty(); }
/** * The value of the property <code>pd</code> of <code>pb</code>, if * * <ul> * <li>it is readable * <li>it is a {@link PersistentBean} * </ul> * * <code>null</code> otherwise (also if there is an exception reading). */ @MethodContract( pre = {@Expression("pb != null"), @Expression("pd != null")}, post = {}) private PersistentBean<?> relatedPeristentBean(PersistentBean<?> pb, PropertyDescriptor pd) { assert pb != null; assert pd != null; PersistentBean<?> result = null; if (PersistentBean.class.isAssignableFrom(pd.getPropertyType())) { Method rm = pd.getReadMethod(); if (rm != null) { // found a property that returns a related bean; get it try { result = (PersistentBean<?>) rm.invoke(pb); } catch (IllegalArgumentException iaExc) { assert false : "Should not happen, since there are no arguments, and the implicit argument is " + "not null and of the correct type"; } catch (IllegalAccessException e) { assert false : "IllegalAccessException should not happen: " + e; } catch (InvocationTargetException e) { assert false : "InvocationTargetException should not happen: " + e; } catch (NullPointerException e) { assert false : "NullPointerException should not happen: " + e; } /* ExceptionInInitializerError can occur with invoke, but we do not take into account errors */ } } return result; }
/** * Examines a property's type to see which method should be used to parse the property's value. * * @param desc The description of the property * @param value The value of the XML attribute containing the prop value * @return The value stored in the element * @throws IOException If there is an error reading the document */ public Object getObjectValue(PropertyDescriptor desc, String value) throws IOException { // Find out what kind of property it is Class type = desc.getPropertyType(); // If it's an array, get the base type if (type.isArray()) { type = type.getComponentType(); } // For native types, object wrappers for natives, and strings, use the // basic parse routine if (type.equals(Integer.TYPE) || type.equals(Long.TYPE) || type.equals(Short.TYPE) || type.equals(Byte.TYPE) || type.equals(Boolean.TYPE) || type.equals(Float.TYPE) || type.equals(Double.TYPE) || Integer.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type) || Short.class.isAssignableFrom(type) || Byte.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type) || Float.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type)) { return parseBasicType(type, value); } else if (String.class.isAssignableFrom(type)) { return value; } else if (java.util.Date.class.isAssignableFrom(type)) { // If it's a date, use the date parser return parseDate(value, JOXDateHandler.determineDateFormat()); } else { return null; } }
public static Object buildBean(Class<?> beanClass, Map<String, String> values) { try { Object obj = null; if (beanClass.isInterface()) { @SuppressWarnings("unchecked") Class<? extends OpenEngSBModel> model = (Class<? extends OpenEngSBModel>) beanClass; obj = ekbService.createEmptyModelObject(model); } else { obj = beanClass.newInstance(); } BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getWriteMethod() == null || !Modifier.isPublic(propertyDescriptor.getWriteMethod().getModifiers())) { continue; } String value = values.get(propertyDescriptor.getName()); Object ob = convertToCorrectClass(propertyDescriptor.getPropertyType(), value); propertyDescriptor.getWriteMethod().invoke(obj, ob); } return obj; } catch (Exception e) { throw new IllegalArgumentException(e); } }
/** * 为对象设置属性 * * @param bean 目标对象 * @param name 属性的名字 * @param value 将要设置的属性值 */ public static void setProperty(Object bean, String name, String value) { Class<?> clazz = bean.getClass(); PropertyDescriptor propertyDescriptor = findPropertyDescriptor(clazz, name); if (propertyDescriptor == null) { try { throw new Exception( "propertyDescriptor is null clazz:" + clazz.getName() + " property name:" + name); } catch (Exception e) { e.printStackTrace(); } } Class<?> type = propertyDescriptor.getPropertyType(); Object newValue = converValue(type, value); Method writeMethod = propertyDescriptor.getWriteMethod(); try { writeMethod.invoke(bean, newValue); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
@Override public Map<String, String> saveOrUpdataReturnCasecadeID( String objectType, HttpServletRequest request) throws Exception { Map<String, String> map = QueryUtil.getRequestParameterMapNoAjax(request); Object targetObject = Class.forName(objectType).newInstance(); String jsonString = map.get(this.getType(objectType).getSimpleName()); String cascadeTypes = map.get("cascadeType"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); Class<?> clazz = this.getType(objectType); targetObject = mapper.readValue(jsonString, clazz); Serializable id = this.commDao.saveOrUpdata(objectType, targetObject); Object target = this.findById(objectType, id.toString()); Map<String, String> returenIDs = new HashMap<String, String>(); returenIDs.put("id", id.toString()); if (cascadeTypes != null) { String[] s = cascadeTypes.split(","); for (int i = 0; i < s.length; i++) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, s[i]); Method method = pd.getReadMethod(); Object childTarget = method.invoke(target); PropertyDescriptor pdID = BeanUtils.getPropertyDescriptor(pd.getPropertyType(), "id"); String childTargetID = pdID.getReadMethod().invoke(childTarget).toString(); returenIDs.put(s[i], childTargetID); } } return returenIDs; }
/** * The upstream {@link PersistentBean PersistentBeans} starting from {@code pb}. These are the * beans that are simple properties of {@code pb}. Upstream means in most cases (this is all that * is implemented at this time) the beans reachable via a to-one association. */ @MethodContract( pre = @Expression("_pb != null"), post = { @Expression("result != null"), @Expression( "for (PropertyDescriptor pd : getPropertyDescriptors(_pb)) {" + "PersistentBean.class.isAssignableFrom(pd.propertyType) && propertyValue(_pb, pd.name) != null ? " + "result.contains(propertyValue(_pb, pd.name))" + "}"), @Expression( "for (PersistentBean pbr : result) {" + "exists (PropertyDescriptor pd : getPropertyDescriptors(_pb)) {" + "pbr == propertyValue(_pb, pd.name)" + "}" + "}") }) public static Set<PersistentBean<?>> directUpstreamPersistentBeans(PersistentBean<?> pb) { assert preArgumentNotNull(pb, "pb"); Set<PersistentBean<?>> result = new HashSet<PersistentBean<?>>(); PropertyDescriptor[] pds = getPropertyDescriptors(pb); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; if (PersistentBean.class.isAssignableFrom(pd.getPropertyType())) { PersistentBean<?> upstreamCandidate = propertyValue(pb, pd.getName()); if (upstreamCandidate != null) { result.add(upstreamCandidate); } } } return result; }
/** * Get the appropriate editor for the given property. * * @param prop Property to get editor for. * @return Editor to use, or null if none found. */ private PropertyEditor getEditorForProperty(PropertyDescriptor prop) { PropertyEditor retval = null; Class type = prop.getPropertyEditorClass(); if (type != null) { try { retval = (PropertyEditor) type.newInstance(); } catch (Exception ex) { ex.printStackTrace(); } } // Handle case where there is no special editor // associated with the property. In that case we ask the // PropertyEditor manager for the editor registered for the // given property type. if (retval == null) { Class t = prop.getPropertyType(); if (t != null) { retval = PropertyEditorManager.findEditor(t); } } // In the worse case we resort to the generic editor for Object types. if (retval == null) { retval = PropertyEditorManager.findEditor(Object.class); } return retval; }
private void refresh() { if (this.value == null) { this.setEnabled(false); return; } this.setEnabled(true); for (final PropertyDescriptor pd : this.beanInfo.getPropertyDescriptors()) { final JTextField field = this.fieldMap.get(pd.getName()); PropertyEditor editor = pd.createPropertyEditor(this.getValue()); if (editor == null) { editor = PropertyEditorManager.findEditor(pd.getPropertyType()); } if (editor == null) { continue; } Object propertyValue = null; try { propertyValue = pd.getReadMethod().invoke(this.getValue()); } catch (final Exception e) { // Just continue continue; } field.setText(propertyValue != null ? propertyValue.toString() : "null"); } }
/** * Compares this <code>PropertyDescriptor</code> against the specified object. Returns true if the * objects are the same. Two <code>PropertyDescriptor</code>s are the same if the read, write, * property types, property editor and flags are equivalent. * * @since 1.4 */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj != null && obj instanceof PropertyDescriptor) { PropertyDescriptor other = (PropertyDescriptor) obj; Method otherReadMethod = other.getReadMethod(); Method otherWriteMethod = other.getWriteMethod(); if (!compareMethods(getReadMethod(), otherReadMethod)) { return false; } if (!compareMethods(getWriteMethod(), otherWriteMethod)) { return false; } if (getPropertyType() == other.getPropertyType() && getPropertyEditorClass() == other.getPropertyEditorClass() && bound == other.isBound() && constrained == other.isConstrained() && writeMethodName == other.writeMethodName && readMethodName == other.readMethodName) { return true; } } return false; }
public static Object parseWithIntrospection( String elementName, Class<?> objectClass, XmlPullParser parser) throws Exception { boolean done = false; Object object = objectClass.newInstance(); while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { String name = parser.getName(); String stringValue = parser.nextText(); PropertyDescriptor descriptor = new PropertyDescriptor(name, objectClass); // Load the class type of the property. Class<?> propertyType = descriptor.getPropertyType(); // Get the value of the property by converting it from a // String to the correct object type. Object value = decode(propertyType, stringValue); // Set the value of the bean. descriptor.getWriteMethod().invoke(object, value); } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals(elementName)) { done = true; } } } return object; }
private List setProperty( Object component, ComponentDescriptor descriptor, ComponentRequirement requirementDescriptor, PropertyDescriptor propertyDescriptor, PlexusContainer container, ClassRealm lookupRealm) throws CompositionException { Requirement requirement = findRequirement( component, propertyDescriptor.getPropertyType(), container, requirementDescriptor, lookupRealm); try { Method writeMethod = propertyDescriptor.getWriteMethod(); Object[] params = new Object[1]; params[0] = requirement.getAssignment(); Statement statement = new Statement(component, writeMethod.getName(), params); statement.execute(); } catch (Exception e) { reportErrorCannotAssignRequiredComponent(descriptor, requirementDescriptor, e); } return requirement.getComponentDescriptors(); }
/** add by xiongcf 得到指定属性名的类型 * */ public Class getDestType(Object bean, String name) { // Validate method parameters if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified"); } // Return the requested result if (bean instanceof DynaBean) { // All DynaBean properties are writeable return null; } else { try { PropertyDescriptor desc = getPropertyDescriptor(bean, name); if (desc != null) { Class c = desc.getPropertyType(); return c; } else { return null; } } catch (IllegalAccessException e) { return null; } catch (InvocationTargetException e) { return null; } catch (NoSuchMethodException e) { return null; } } }
private ObjectConverter generateConverter(Class cls) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(cls); } catch (IntrospectionException e) { throw new RuntimeException(e); } PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); List<ObjectConverterEntry> list = new ArrayList<ObjectConverterEntry>(); for (int i = 0, length = props.length; i < length; i++) { PropertyDescriptor prop = props[i]; if ("class".equals(prop.getName())) { continue; } list.add( new ObjectConverterEntry( prop.getName(), prop.getReadMethod(), getType(prop.getPropertyType()))); } return new ObjectConverter(cls, list.toArray(new ObjectConverterEntry[list.size()])); }
private void setAttributes( JrdsElement probeNode, Object o, Map<String, PropertyDescriptor> beans, Object... context) throws IllegalArgumentException, InvocationTargetException { // Resolve the beans for (JrdsElement attrNode : probeNode.getChildElementsByName("attr")) { String name = attrNode.getAttribute("name"); PropertyDescriptor bean = beans.get(name); if (bean == null) { logger.error("Unknonw bean " + name); continue; } String textValue = Util.parseTemplate(attrNode.getTextContent(), context); logger.trace(Util.delayedFormatString("Fond attribute %s with value %s", name, textValue)); try { Constructor<?> c = bean.getPropertyType().getConstructor(String.class); Object value = c.newInstance(textValue); bean.getWriteMethod().invoke(o, value); } catch (IllegalArgumentException e) { throw new InvocationTargetException(e, HostBuilder.class.getName()); } catch (SecurityException e) { throw new InvocationTargetException(e, HostBuilder.class.getName()); } catch (InstantiationException e) { throw new InvocationTargetException(e, HostBuilder.class.getName()); } catch (IllegalAccessException e) { throw new InvocationTargetException(e, HostBuilder.class.getName()); } catch (InvocationTargetException e) { throw new InvocationTargetException(e, HostBuilder.class.getName()); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, HostBuilder.class.getName()); } } }