Java Code Examples for java.beans.PropertyDescriptor#getName()
The following examples show how to use
java.beans.PropertyDescriptor#getName() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Test4634390.java From hottub with GNU General Public License v2.0 | 6 votes |
private static void test(Class type) { for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(type)) { PropertyDescriptor pdCopy = create(pd); if (pdCopy != null) { // XXX - hack! The Introspector will set the bound property // since it assumes that propertyChange event set descriptors // infers that all the properties are bound pdCopy.setBound(pd.isBound()); String name = pd.getName(); System.out.println(" - " + name); if (!compare(pd, pdCopy)) throw new Error("property delegates are not equal"); if (!pd.equals(pdCopy)) throw new Error("equals() failed"); if (pd.hashCode() != pdCopy.hashCode()) throw new Error("hashCode() failed"); } } }
Example 2
Source File: BeanUtils.java From tools with MIT License | 6 votes |
/** * bean转map * * @param bean bean对象 * @return map */ public static Map<String, Object> toMap(Object bean) { Map<String, Object> map = new HashMap<>(); try { BeanInfo beaninfo = Introspector.getBeanInfo(bean.getClass(), Object.class); PropertyDescriptor[] pro = beaninfo.getPropertyDescriptors(); for (PropertyDescriptor property : pro) { String key = property.getName(); Method get = property.getReadMethod(); Object value = get.invoke(bean); map.put(key, value); } } catch (Exception e) { e.printStackTrace(); } return map; }
Example 3
Source File: ExtendedBeanInfo.java From java-technology-stack with MIT License | 6 votes |
@Nullable 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; }
Example 4
Source File: Test4634390.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
private static PropertyDescriptor create(PropertyDescriptor pd) { try { if (pd instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd; return new IndexedPropertyDescriptor( ipd.getName(), ipd.getReadMethod(), ipd.getWriteMethod(), ipd.getIndexedReadMethod(), ipd.getIndexedWriteMethod()); } else { return new PropertyDescriptor( pd.getName(), pd.getReadMethod(), pd.getWriteMethod()); } } catch (IntrospectionException exception) { exception.printStackTrace(); return null; } }
Example 5
Source File: BeanUtils.java From SuperBoot with MIT License | 6 votes |
/** * 复制Map属性 * * @param source * @param target * @throws BeansException */ public static void copyProperties(Map source, Object target) throws BeansException { Iterator<Map.Entry> s = source.entrySet().iterator(); //获取目标对象所有属性 PropertyDescriptor[] targetPds = getPropertyDescriptors(target.getClass()); for (PropertyDescriptor targetPd : targetPds) { //获取目标对象属性写方法 Method writeMethod = targetPd.getWriteMethod(); if (null != writeMethod) { try { while (s.hasNext()) { Map.Entry en = s.next(); if (en.getKey().equals(targetPd.getName())) { //如果方法访问权限不足,设置方法允许访问权限 if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, new Object[]{en.getValue()}); } } } catch (Throwable var15) { throw new FatalBeanException("Could not copy property \'" + targetPd.getName() + "\' from source to target", var15); } } } }
Example 6
Source File: Configuration.java From gflogger with Apache License 2.0 | 6 votes |
private void startLogger(Attributes attributes) throws Exception { final GFLoggerBuilder builder = new GFLoggerBuilder(); for ( final PropertyDescriptor property : BeanUtils.classProperties( builder.getClass() ) ) { final String propertyName = property.getName(); if ( property.getWriteMethod() != null ) { BeanUtils.setPropertyStringValue( builder, property, getAttribute( attributes, propertyName ) ); } } final String name = builder.getName(); debug("Created " + (name != null ? "'" + name + "'" : "root") + " logger"); stack.push(builder); }
Example 7
Source File: BeanMapUtil.java From zooadmin with MIT License | 6 votes |
/** * 将对象转为Map,为null的字段跳过,同时保持有序 * @param bean * @return * @throws IntrospectionException * @throws IllegalAccessException * @throws InvocationTargetException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Map bean2MapNull(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException { Class type = bean.getClass(); Map returnMap = new TreeMap(); BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo .getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (result != null) { returnMap.put(propertyName, result); } else { //没有值的字段直接跳过 } } } return returnMap; }
Example 8
Source File: Cloneable.java From lams with GNU General Public License v2.0 | 6 votes |
private void internalCheckListeners(BeanInfo beanInfo) { PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); try { for ( PropertyDescriptor pd : pds ) { final Object listener = pd.getReadMethod().invoke( this, READER_METHOD_ARGS ); if ( listener == null ) { throw new HibernateException( "Listener [" + pd.getName() + "] was null" ); } if ( listener.getClass().isArray() ) { Object[] listenerArray = (Object[]) listener; for ( Object aListenerArray : listenerArray ) { if ( aListenerArray == null ) { throw new HibernateException( "Listener in [" + pd.getName() + "] was null" ); } } } } } catch (HibernateException e) { throw e; } catch (Throwable t) { throw new HibernateException( "Unable to validate listener config" ); } }
Example 9
Source File: Test4634390.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
private static PropertyDescriptor create(PropertyDescriptor pd) { try { if (pd instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd; return new IndexedPropertyDescriptor( ipd.getName(), ipd.getReadMethod(), ipd.getWriteMethod(), ipd.getIndexedReadMethod(), ipd.getIndexedWriteMethod()); } else { return new PropertyDescriptor( pd.getName(), pd.getReadMethod(), pd.getWriteMethod()); } } catch (IntrospectionException exception) { exception.printStackTrace(); return null; } }
Example 10
Source File: BeanUtils.java From SuperBoot with MIT License | 6 votes |
/** * 复制实体属性到map * * @param source * @param target * @throws BeansException */ public static void copyProperties(Object source, Map target) throws BeansException { PropertyDescriptor[] sourcePds = getPropertyDescriptors(source.getClass()); for (PropertyDescriptor sourcePd : sourcePds) { Method readMethod = sourcePd.getReadMethod(); if (null != readMethod) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); target.put(sourcePd.getName(), value); } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + sourcePd.getName() + "' from source to target", ex); } } } }
Example 11
Source File: PropertyMatches.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Generate possible property alternatives for the given property and * class. Internally uses the {@code getStringDistance} method, which * in turn uses the Levenshtein algorithm to determine the distance between * two Strings. * @param propertyDescriptors the JavaBeans property descriptors to search * @param maxDistance the maximum distance to accept */ private static String[] calculateMatches(String propertyName, PropertyDescriptor[] propertyDescriptors, int maxDistance) { List<String> candidates = new ArrayList<String>(); for (PropertyDescriptor pd : propertyDescriptors) { if (pd.getWriteMethod() != null) { String possibleAlternative = pd.getName(); if (calculateStringDistance(propertyName, possibleAlternative) <= maxDistance) { candidates.add(possibleAlternative); } } } Collections.sort(candidates); return StringUtils.toStringArray(candidates); }
Example 12
Source File: PropertyMatches.java From blog_demos with Apache License 2.0 | 5 votes |
/** * Generate possible property alternatives for the given property and * class. Internally uses the {@code getStringDistance} method, which * in turn uses the Levenshtein algorithm to determine the distance between * two Strings. * @param propertyDescriptors the JavaBeans property descriptors to search * @param maxDistance the maximum distance to accept */ private String[] calculateMatches(PropertyDescriptor[] propertyDescriptors, int maxDistance) { List<String> candidates = new ArrayList<String>(); for (PropertyDescriptor pd : propertyDescriptors) { if (pd.getWriteMethod() != null) { String possibleAlternative = pd.getName(); if (calculateStringDistance(this.propertyName, possibleAlternative) <= maxDistance) { candidates.add(possibleAlternative); } } } Collections.sort(candidates); return StringUtils.toStringArray(candidates); }
Example 13
Source File: ModelBuilder.java From ccu-historian with GNU General Public License v3.0 | 5 votes |
/** * Creates a {@link PropertyInfo} object from a {@link PropertyDescriptor}. * * @param pd the property descriptor. * * @return the property info (<code>null</code> possible). */ public PropertyInfo createSimplePropertyInfo(final PropertyDescriptor pd) { final boolean readMethod = isValidMethod(pd.getReadMethod()); final boolean writeMethod = isValidMethod(pd.getWriteMethod()); if (!writeMethod || !readMethod) { // a property is useless for our purposes without having a read or write method. return null; } final PropertyInfo pi = new PropertyInfo(pd.getName(), pd.getPropertyType()); pi.setConstrained(pd.isConstrained()); pi.setDescription(pd.getShortDescription()); pi.setNullable(true); pi.setPreserve(false); pi.setReadMethodAvailable(readMethod); pi.setWriteMethodAvailable(writeMethod); pi.setXmlName(pd.getName()); if (isAttributeProperty(pd.getPropertyType())) { pi.setPropertyType(PropertyType.ATTRIBUTE); pi.setXmlHandler(getHandlerClass(pd.getPropertyType())); } else { pi.setPropertyType(PropertyType.ELEMENT); } return pi; }
Example 14
Source File: PropertyDTO.java From fabric8-forge with Apache License 2.0 | 5 votes |
public PropertyDTO(PropertyDescriptor propertyDescriptor) { name = propertyDescriptor.getName(); displayName = propertyDescriptor.getDisplayName(); typeClass = propertyDescriptor.getPropertyType(); typeName = typeClass.getName(); description = propertyDescriptor.getShortDescription(); readable = propertyDescriptor.getReadMethod() != null; writeable = propertyDescriptor.getWriteMethod() != null; }
Example 15
Source File: AbstractSampleRandomGroupsController.java From proctor with Apache License 2.0 | 5 votes |
@Override public String printProctorContext(final ProctorContext proctorContext) { final StringBuilder sb = new StringBuilder(); final BeanWrapper beanWrapper = new BeanWrapperImpl(proctorContext); for (final PropertyDescriptor descriptor : beanWrapper.getPropertyDescriptors()) { final String propertyName = descriptor.getName(); if (!"class".equals(propertyName)) { // ignore class property which every object has final Object propertyValue = beanWrapper.getPropertyValue(propertyName); sb.append(propertyName).append(": '").append(propertyValue).append("'").append("\n"); } } return sb.toString(); }
Example 16
Source File: LogicalPlan.java From attic-apex-core with Apache License 2.0 | 4 votes |
protected void populateAggregatorMeta() { AutoMetric.Aggregator aggregator = getValue(OperatorContext.METRICS_AGGREGATOR); if (aggregator == null && operator instanceof AutoMetric.Aggregator) { aggregator = new MetricAggregatorMeta.MetricsAggregatorProxy(this); } if (aggregator == null) { MetricsAggregator defAggregator = null; Set<String> metricNames = Sets.newHashSet(); for (Field field : ReflectionUtils.getDeclaredFieldsIncludingInherited(operator.getClass())) { if (field.isAnnotationPresent(AutoMetric.class)) { metricNames.add(field.getName()); if (field.getType() == int.class || field.getType() == Integer.class || field.getType() == long.class || field.getType() == Long.class) { if (defAggregator == null) { defAggregator = new MetricsAggregator(); } defAggregator.addAggregators(field.getName(), new SingleMetricAggregator[]{new LongSumAggregator()}); } else if (field.getType() == float.class || field.getType() == Float.class || field.getType() == double.class || field.getType() == Double.class) { if (defAggregator == null) { defAggregator = new MetricsAggregator(); } defAggregator.addAggregators(field.getName(), new SingleMetricAggregator[]{new DoubleSumAggregator()}); } } } try { for (PropertyDescriptor pd : Introspector.getBeanInfo(operator.getClass()).getPropertyDescriptors()) { Method readMethod = pd.getReadMethod(); if (readMethod != null) { AutoMetric rfa = readMethod.getAnnotation(AutoMetric.class); if (rfa != null) { String propName = pd.getName(); if (metricNames.contains(propName)) { continue; } if (readMethod.getReturnType() == int.class || readMethod.getReturnType() == Integer.class || readMethod.getReturnType() == long.class || readMethod.getReturnType() == Long.class) { if (defAggregator == null) { defAggregator = new MetricsAggregator(); } defAggregator.addAggregators(propName, new SingleMetricAggregator[]{new LongSumAggregator()}); } else if (readMethod.getReturnType() == float.class || readMethod.getReturnType() == Float.class || readMethod.getReturnType() == double.class || readMethod.getReturnType() == Double.class) { if (defAggregator == null) { defAggregator = new MetricsAggregator(); } defAggregator.addAggregators(propName, new SingleMetricAggregator[]{new DoubleSumAggregator()}); } } } } } catch (IntrospectionException e) { throw new RuntimeException("finding methods", e); } if (defAggregator != null) { aggregator = defAggregator; } } this.metricAggregatorMeta = new MetricAggregatorMeta(aggregator, getValue(OperatorContext.METRICS_DIMENSIONS_SCHEME)); }
Example 17
Source File: BeanUtils.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Copy the property values of the given source bean into the given target bean. * <p>Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * @param source the source bean * @param target the target bean * @param editable the class (or interface) to restrict property setting to * @param ignoreProperties array of property names to ignore * @throws BeansException if the copying failed * @see BeanWrapper */ private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); } actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null); for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } } } }
Example 18
Source File: FiltersUtils.java From jivejdon with Apache License 2.0 | 4 votes |
public static String getPropertyHTML(Function<MessageVO, MessageVO> filter, PropertyDescriptor descriptor) { // HTML of the customizer for this property StringBuilder html = new StringBuilder(50); // Get the name of the property (this becomes the name of the form // element) String propName = descriptor.getName(); // Get the current value of the property Object propValue = null; try { Method methodc = descriptor.getReadMethod(); // Decode the property value using the property type and // encoded String value. Object[] args = null; propValue = methodc.invoke(filter, args); } catch (Exception e) { e.printStackTrace(); } // Get the classname of this property String className = descriptor.getPropertyType().getName(); // HTML form elements for number values (rendered as small textfields) if ("int".equals(className) || "double".equals(className) || "long".equals(className)) { html.append("<input type=\"text\" name=\"").append(propName).append("\" size=\"100\" "); if (propValue != null) { html.append(" value=\"").append(propValue.toString()).append("\""); } html.append(">"); } // HTML form elements for boolean values (rendered as Yes/No radio // buttons) else if ("boolean".equals(className)) { boolean value = false; if ("true".equals(propValue.toString())) { value = true; } html.append("<input type=\"radio\" name=\"").append(propName).append("\" id=\"rb").append(propName).append("1\" "); html.append("value=\"true\""); html.append((value) ? " checked" : ""); html.append("> <label for=\"rb").append(propName).append("1\">Yes</label> "); html.append("<input type=\"radio\" name=\"").append(propName).append("\" id=\"rb").append(propName).append("2\" "); html.append("value=\"false\""); html.append((!value) ? " checked" : ""); html.append("> <label for=\"rb").append(propName).append("2\">No</label> "); } // HTML elements for a String (rendered as a wide textfield) else if ("java.lang.String".equals(className)) { if (propName.toLowerCase().equals("password")) { html.append("<input type=\"password\""); } else { html.append("<input type=\"text\""); } html.append(" name=\"").append(propName).append("\" size=\"100\" "); if (propValue != null) { html.append(" value=\"").append(escapeHTML(propValue.toString())).append("\""); } html.append(">"); } if (html.length() == 0) { html.append(" "); } return html.toString().intern(); }
Example 19
Source File: BeanDiff.java From jaxb2-rich-contract-plugin with MIT License | 4 votes |
private String createPropertyString(final Object obj, final PropertyDescriptor property) { return property.getPropertyType().getName() + " " + property.getReadMethod().getDeclaringClass().getName() + "." + property.getName() + " (" + obj + ")"; }
Example 20
Source File: ExpressionMetaGenerator.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 4 votes |
public static void main( String[] args ) throws IOException, IntrospectionException { ClassicEngineBoot.getInstance().start(); ExpressionQueryTool eqt = new ExpressionQueryTool(); eqt.processDirectory( null ); final Class[] classes = eqt.getExpressions(); final DefaultTagDescription dtd = new DefaultTagDescription(); dtd.setNamespaceHasCData( META_NAMESPACE, false ); final XmlWriter writer = new XmlWriter( new PrintWriter( System.out ), dtd ); final AttributeList attrList = new AttributeList(); attrList.addNamespaceDeclaration( "", META_NAMESPACE ); writer.writeTag( META_NAMESPACE, "meta-data", attrList, XmlWriter.OPEN ); for ( int i = 0; i < classes.length; i++ ) { final Class aClass = classes[ i ]; if ( OutputFunction.class.isAssignableFrom( aClass ) ) { // Output functions will not be recognized. continue; } if ( aClass.getName().indexOf( '$' ) >= 0 ) { // Inner-Classes will not be recognized. continue; } final AttributeList expressionAttrList = new AttributeList(); expressionAttrList.setAttribute( META_NAMESPACE, "class", aClass.getName() ); expressionAttrList .setAttribute( META_NAMESPACE, "bundle-name", "org.pentaho.reporting.engine.classic.core.metadata.messages" ); expressionAttrList.setAttribute( META_NAMESPACE, "result", "java.lang.Object" ); expressionAttrList.setAttribute( META_NAMESPACE, "expert", "false" ); expressionAttrList.setAttribute( META_NAMESPACE, "hidden", "false" ); expressionAttrList.setAttribute( META_NAMESPACE, "preferred", "false" ); writer.writeTag( META_NAMESPACE, "expression", expressionAttrList, XmlWriter.OPEN ); final BeanInfo beanInfo = Introspector.getBeanInfo( aClass ); final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for ( int j = 0; j < descriptors.length; j++ ) { final PropertyDescriptor descriptor = descriptors[ j ]; final String key = descriptor.getName(); if ( "runtime".equals( key ) ) { continue; } if ( "active".equals( key ) ) { continue; } if ( "preserve".equals( key ) ) { continue; } if ( descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null ) { continue; } final AttributeList propAttrList = new AttributeList(); propAttrList.setAttribute( META_NAMESPACE, "name", descriptor.getName() ); if ( "name".equals( key ) ) { propAttrList.setAttribute( META_NAMESPACE, "mandatory", "true" ); propAttrList.setAttribute( META_NAMESPACE, "preferred", "true" ); propAttrList.setAttribute( META_NAMESPACE, "value-role", "Name" ); propAttrList.setAttribute( META_NAMESPACE, "expert", "false" ); } else { propAttrList.setAttribute( META_NAMESPACE, "mandatory", "false" ); propAttrList.setAttribute( META_NAMESPACE, "preferred", "false" ); propAttrList.setAttribute( META_NAMESPACE, "value-role", "Value" ); if ( "dependencyLevel".equals( key ) ) { propAttrList.setAttribute( META_NAMESPACE, "expert", "true" ); } else { propAttrList.setAttribute( META_NAMESPACE, "expert", "false" ); } } propAttrList.setAttribute( META_NAMESPACE, "hidden", "false" ); writer.writeTag( META_NAMESPACE, "property", propAttrList, XmlWriter.CLOSE ); } writer.writeCloseTag(); } writer.writeCloseTag(); writer.flush(); }