List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors
public static PropertyDescriptor[] getPropertyDescriptors(Object bean)
Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.
For more details see PropertyUtilsBean
.
From source file:com.wavemaker.runtime.service.ElementType.java
/** * Create an ElementType with one level of children (populated by looking at the bean properties of javaType). This * method should not be used recursively. *///from w w w . j a v a 2s . c o m public ElementType(String name, Class<?> javaType, boolean isList) { this(name, javaType.getName(), isList); PropertyDescriptor[] pds; pds = PropertyUtils.getPropertyDescriptors(javaType); List<ElementType> elements = new ArrayList<ElementType>(pds.length); for (PropertyDescriptor pd : pds) { if (pd.getName().equals("class")) { continue; } if (pd.getReadMethod() == null && pd.getWriteMethod() == null) { continue; } Class<?> klass; Type type; if (pd.getReadMethod() != null) { klass = pd.getReadMethod().getReturnType(); type = pd.getReadMethod().getGenericReturnType(); } else { klass = pd.getWriteMethod().getParameterTypes()[0]; type = pd.getWriteMethod().getGenericParameterTypes()[0]; } ElementType element; if (klass.isArray()) { element = new ElementType(pd.getName(), klass.getComponentType().getName(), true); } else if (Collection.class.isAssignableFrom(klass) && type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; Type aType = ptype.getActualTypeArguments()[0]; element = new ElementType(pd.getName(), ((Class<?>) aType).getName(), true); } else { element = new ElementType(pd.getName(), klass.getName()); } elements.add(element); } this.properties = elements; }
From source file:com.dp2345.template.directive.BaseDirective.java
/** * ?//from w w w . j a v a 2 s . co m * * @param params * ? * @param type * ? * @param ignoreProperties * * @return */ protected List<Filter> getFilters(Map<String, TemplateModel> params, Class<?> type, String... ignoreProperties) throws TemplateModelException { List<Filter> filters = new ArrayList<Filter>(); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); Class<?> propertyType = propertyDescriptor.getPropertyType(); if (!ArrayUtils.contains(ignoreProperties, propertyName) && params.containsKey(propertyName)) { Object value = FreemarkerUtils.getParameter(propertyName, propertyType, params); filters.add(Filter.eq(propertyName, value)); } } return filters; }
From source file:de.knightsoftnet.validators.rebind.GwtReflectGetterGenerator.java
@Override public final String generate(final TreeLogger plogger, final GeneratorContext pcontext, final String ptypeName) throws UnableToCompleteException { try {/*from w w w. java 2 s. c o m*/ plogger.log(TreeLogger.DEBUG, "Start generating for " + ptypeName + "."); final JClassType classType = pcontext.getTypeOracle().getType(ptypeName); final TypeOracle typeOracle = pcontext.getTypeOracle(); assert typeOracle != null; final JClassType reflectorType = this.findType(plogger, typeOracle, ptypeName); // here you would retrieve the metadata based on typeName for this class final SourceWriter src = this.getSourceWriter(classType, pcontext, plogger); // generator is called more then once in a build, with second call, we don't get // a writer and needn't generate the class once again if (src != null) { final Class<?>[] classes = this.getBeans(plogger, reflectorType); src.println("@Override"); src.println("public final Object getProperty(final Object pbean, final String pname)" + " throws NoSuchMethodException, ReflectiveOperationException {"); src.println(" if (pbean == null) {"); src.println(" throw new NoSuchMethodException(\"A null object has no getters\");"); src.println(" }"); src.println(" if (pname == null) {"); src.println(" throw new NoSuchMethodException(\"No method to get property for null\");"); src.println(" }"); src.println(StringUtils.EMPTY); for (final Class<?> clazz : classes) { final String className = clazz.getName(); plogger.log(TreeLogger.DEBUG, "Generating getter reflections for class " + className); // Describe the bean properties final PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(clazz); src.println(" if (pbean.getClass() == " + className + ".class) {"); src.println(" switch (pname) {"); // for all getters generate a case and return entry for (final PropertyDescriptor property : properties) { final Method readMethod = property.getReadMethod(); final String name = property.getName(); if (readMethod == null) { continue; // If the property cannot be read } plogger.log(TreeLogger.DEBUG, "Add getter for property " + name); // Invoke the getter on the bean src.println(" case \"" + name + "\":"); src.println(" return ((" + className + ") pbean)." + readMethod.getName() + "();"); } src.println(" default:"); src.println(" throw new NoSuchMethodException(\"Class " + className + " has no getter for porperty \" + pname);"); src.println(" }"); src.println(" }"); } src.println(" throw new ReflectiveOperationException(\"Class \" + " + "pbean.getClass().getName() + \" is not reflected\");"); src.println("}"); plogger.log(TreeLogger.DEBUG, "End of generating reached"); src.commit(plogger); } return this.getClassPackage(classType) + "." + this.getClassName(classType); } catch (final NotFoundException e) { e.printStackTrace(); } return null; }
From source file:ca.sqlpower.testutil.TestUtils.java
/** * Gets all the settable properties on the given target object * which are not in the given ignore set, and stuffs them into a Map. * // ww w . j a va 2s. c om * @param target The object to change the properties of * @param propertiesToIgnore The properties of target not to modify or read * @return The aforementioned stuffed map */ public static Map<String, Object> getAllInterestingProperties(Object target, Set<String> propertiesToIgnore) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Map<String, Object> newDescription = new HashMap<String, Object>(); PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(target); for (int i = 0; i < props.length; i++) { if (PropertyUtils.isReadable(target, props[i].getName()) && props[i].getReadMethod() != null && !propertiesToIgnore.contains(props[i].getName())) { newDescription.put(props[i].getName(), PropertyUtils.getProperty(target, props[i].getName())); } } return newDescription; }
From source file:com.ettrema.httpclient.calsync.parse.BeanPropertyMapper.java
/** * Find a property with the given annotation and return its value * * @param bean//from w w w .j a v a 2 s. c o m * @param annotationClass * @return */ public <T> T getProperty(Object bean, Class annotationClass, Class<T> valueClass) { PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean); for (PropertyDescriptor pd : pds) { if (pd.getReadMethod() != null && pd.getWriteMethod() != null) { Method read = pd.getReadMethod(); Annotation[] annotations = read.getAnnotations(); for (Annotation anno : annotations) { if (anno.annotationType() == annotationClass) { return propertyAccessor.get(bean, read, valueClass); } } } } return null; }
From source file:ca.sqlpower.matchmaker.MatchMakerTestCase.java
public void testDuplicate() throws Exception { MatchMakerObject mmo = getTarget();/* ww w . ja v a2 s . co m*/ List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(mmo.getClass())); propertiesToIgnoreForDuplication.add("defaultInputClass"); propertiesToIgnoreForDuplication.add("parameters"); propertiesToIgnoreForDuplication.add("MSOInputs"); propertiesToIgnoreForDuplication.add("UUID"); propertiesToIgnoreForDuplication.add("oid"); propertiesToIgnoreForDuplication.add("parent"); propertiesToIgnoreForDuplication.add("parentProject"); propertiesToIgnoreForDuplication.add("session"); propertiesToIgnoreForDuplication.add("allowedChildTypes"); propertiesToIgnoreForDuplication.add("cachableTable"); propertiesToIgnoreForDuplication.add("cachableColumn"); propertiesToIgnoreForDuplication.add("importedCachableColumn"); propertiesToIgnoreForDuplication.add("class"); propertiesToIgnoreForDuplication.add("createDate"); propertiesToIgnoreForDuplication.add("createAppUser"); propertiesToIgnoreForDuplication.add("createOsUser"); propertiesToIgnoreForDuplication.add("dependencies"); propertiesToIgnoreForDuplication.add("children"); propertiesToIgnoreForDuplication.add("lastUpdateDate"); propertiesToIgnoreForDuplication.add("lastUpdateAppUser"); propertiesToIgnoreForDuplication.add("lastUpdateOSUser"); propertiesToIgnoreForDuplication.add("magicEnabled"); propertiesToIgnoreForDuplication.add("mergingEngine"); propertiesToIgnoreForDuplication.add("matchingEngine"); propertiesToIgnoreForDuplication.add("cleansingEngine"); propertiesToIgnoreForDuplication.add("addressCorrectionEngine"); propertiesToIgnoreForDuplication.add("addressCommittingEngine"); propertiesToIgnoreForDuplication.add("undoing"); propertiesToIgnoreForDuplication.add("results"); propertiesToIgnoreForDuplication.add("runningEngine"); propertiesToIgnoreForDuplication.add("runnableDispatcher"); propertiesToIgnoreForDuplication.add("workspaceContainer"); propertiesToIgnoreForDuplication.add("tableMergeRules"); propertiesToIgnoreForDuplication.add("resultStep"); propertiesToIgnoreForDuplication.add("inputSteps"); propertiesToIgnoreForDuplication.add("mungeSteps"); propertiesToIgnoreForDuplication.add("projects"); propertiesToIgnoreForDuplication.add("JDBCDataSource"); propertiesToIgnoreForDuplication.add("table"); propertiesToIgnoreForDuplication.add("tableIndex"); propertiesToIgnoreForDuplication.add("columnMergeRules"); propertiesToIgnoreForDuplication.add("inputs"); propertiesToIgnoreForDuplication.add("mungeStepOutputs"); propertiesToIgnoreForDuplication.add("parameterNames"); propertiesToIgnoreForDuplication.add("project"); propertiesToIgnoreForDuplication.add("addressStatus"); propertiesToIgnoreForDuplication.add("addressDB"); propertiesToIgnoreForDuplication.add("open"); propertiesToIgnoreForDuplication.add("expanded"); propertiesToIgnoreForDuplication.add("position"); propertiesToIgnoreForDuplication.add("inputCount"); propertiesToIgnoreForDuplication.add("matchPool"); propertiesToIgnoreForDuplication.add("resultTableCatalog"); propertiesToIgnoreForDuplication.add("resultTableName"); propertiesToIgnoreForDuplication.add("resultTableSchema"); propertiesToIgnoreForDuplication.add("resultTableSPDataSource"); propertiesToIgnoreForDuplication.add("sourceTableCatalog"); propertiesToIgnoreForDuplication.add("sourceTableName"); propertiesToIgnoreForDuplication.add("sourceTableSchema"); propertiesToIgnoreForDuplication.add("sourceTableSPDataSource"); propertiesToIgnoreForDuplication.add("xrefTableCatalog"); propertiesToIgnoreForDuplication.add("xrefTableName"); propertiesToIgnoreForDuplication.add("xrefTableSchema"); propertiesToIgnoreForDuplication.add("xrefTableSPDataSource"); //this throws an exception if the DS does not exist propertiesToIgnoreForDuplication.add("spDataSource"); // First pass: set all settable properties, because testing the duplication of // an object with all its properties at their defaults is not a // very convincing test of duplication! for (PropertyDescriptor property : settableProperties) { if (propertiesToIgnoreForDuplication.contains(property.getName())) continue; Object oldVal; try { oldVal = PropertyUtils.getSimpleProperty(mmo, property.getName()); // check for a setter if (property.getWriteMethod() != null && !property.getName().equals("children")) { Object newVal = getNewDifferentValue(mmo, property, oldVal); BeanUtils.copyProperty(mmo, property.getName(), newVal); } } catch (NoSuchMethodException e) { System.out.println( "Skipping non-settable property " + property.getName() + " on " + mmo.getClass().getName()); } } // Second pass get a copy make sure all of // the original mutable objects returned from getters are different // between the two objects, but have the same values. MatchMakerObject duplicate = mmo.duplicate((MatchMakerObject) mmo.getParent()); for (PropertyDescriptor property : settableProperties) { if (propertiesToIgnoreForDuplication.contains(property.getName())) continue; Object oldVal; try { oldVal = PropertyUtils.getSimpleProperty(mmo, property.getName()); /* * If this value is an unmodifiable list, it is then going to be a property * we do not wish to test duplication for, like the children lists. This * is a way to catch them all at once. */ boolean listIsModifiable = true; if (oldVal instanceof List) { List l = (List) oldVal; try { l.add("test"); l.remove("test"); } catch (UnsupportedOperationException e) { listIsModifiable = false; } } if (listIsModifiable) { Object copyVal = PropertyUtils.getSimpleProperty(duplicate, property.getName()); if (oldVal == null) { throw new NullPointerException("We forgot to set " + property.getName()); } else { if (oldVal instanceof MungeStep) { MungeStep oldStep = (MungeStep) oldVal; MungeStep copyStep = (MungeStep) copyVal; assertNotSame("The two MungeStep's share the same instance.", oldVal, copyVal); assertEquals("The two names are different.", oldStep.getName(), copyStep.getName()); assertEquals("The two visible properties are different.", oldStep.isVisible(), copyStep.isVisible()); } else { assertEquals("The two values for property " + property.getDisplayName() + " in " + mmo.getClass().getName() + " should be equal", oldVal, copyVal); if (propertiesShareInstanceForDuplication.contains(property.getName())) return; /* * Ok, the duplicate object's property value compared equal. * Now we want to make sure if we modify that property on the original, * it won't affect the copy. */ Object newCopyVal = modifyObject(mmo, property, copyVal); assertFalse( "The two values are the same mutable object for property " + property.getDisplayName() + " was " + oldVal + " and " + copyVal, oldVal.equals(newCopyVal)); } } } } catch (NoSuchMethodException e) { System.out.println( "Skipping non-settable property " + property.getName() + " on " + mmo.getClass().getName()); } } }
From source file:com.afeng.common.utils.reflection.MyBeanUtils.java
public static void copyBean2Map(Map map, Object bean) { PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; String propname = pd.getName(); try {//www . j a v a 2 s .c o m Object propvalue = PropertyUtils.getSimpleProperty(bean, propname); map.put(propname, propvalue); } catch (IllegalAccessException e) { //e.printStackTrace(); } catch (InvocationTargetException e) { //e.printStackTrace(); } catch (NoSuchMethodException e) { //e.printStackTrace(); } } }
From source file:com.ksmpartners.ernie.util.TestUtil.java
/** * Performs the getter/setter tests on the java object. The method works by * iterating over the declared fields (ignoring static fields) and ensures * that each field has a getter and setter (as indicated by the parameters) * and that the results of calling the setter followed by the getter match. * <p>// w w w. ja va 2 s .co m */ public static void populateFields(Class clazz, Object target) { PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(target); for (PropertyDescriptor property : properties) { final String qName = "[" + clazz.getName() + "]." + property.getName(); final Class<?> fieldType = property.getPropertyType(); // ignore getClass() and isEmpty() if (property.getName().equals("class") || property.getName().equals("empty")) continue; // create a test value for our setter Object setValue = createSetValue(qName, fieldType); testProperty(target, property, setValue, qName); } }
From source file:it.sample.parser.util.CommonsUtil.java
/** * Metodo di utilita' che copia i campi non nulli della classe sorgente in quelli della classe di destinazione * /* ww w . j a v a2 s . c o m*/ * @param source * @param destination */ public static <K, T> void copyNotNullProperties(K source, T destination) { PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(source); if (descriptors != null) { for (PropertyDescriptor descriptor : descriptors) { try { String propertyName = descriptor.getName(); Field field = getDeclaredField(propertyName, source.getClass()); if (field != null && field.getAnnotation(IgnoreField.class) == null) { boolean wasAccessible = field.isAccessible(); field.setAccessible(true); if (PropertyUtils.getReadMethod(descriptor) != null) { Object val = PropertyUtils.getSimpleProperty(source, propertyName); if (val != null && descriptor.getWriteMethod() != null) { PropertyUtils.setProperty(destination, propertyName, val); } } field.setAccessible(wasAccessible); } } catch (Exception e) { e.printStackTrace(); } } } }
From source file:com.panemu.tiwulfx.control.LookupFieldController.java
/** * Show lookup dialog.// w ww . j a v a 2 s .co m * * @param stage parent * @param initialValue this value will be returned if user clik the close * button instead of double clicking a row or click Select button * @param propertyName propertyName corresponds to searchCriteria * @param searchCriteria searchCriteria (nullable) * @return selected object or the initialValue */ public T show(final Window stage, T initialValue, String propertyName, String searchCriteria) { if (dialogStage == null) { PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(recordClass); lookupWindow = new LookupWindow(); for (String clm : getColumns()) { for (PropertyDescriptor prop : props) { if (prop.getName().equals(clm)) { Class type = prop.getPropertyType(); if (type.equals(Boolean.class)) { lookupWindow.table.addColumn(new CheckBoxColumn<T>(clm)); } else if (type.equals(String.class)) { lookupWindow.table.addColumn(new TextColumn<T>(clm)); } else if (type.equals(Date.class)) { lookupWindow.table.addColumn(new LocalDateColumn<T>(clm)); } else if (Number.class.isAssignableFrom(type)) { if (Long.class.isAssignableFrom(type)) { lookupWindow.table.addColumn(new NumberColumn<T, Long>(clm, type)); } else { lookupWindow.table.addColumn(new NumberColumn<T, Double>(clm, type)); } } else { TableColumn column = new TableColumn(); column.setCellValueFactory(new PropertyValueFactory(clm)); lookupWindow.table.addColumn(column); } break; } } } dialogStage = new Stage(); if (stage instanceof Stage) { dialogStage.initOwner(stage); dialogStage.initModality(Modality.WINDOW_MODAL); } else { dialogStage.initOwner(null); dialogStage.initModality(Modality.APPLICATION_MODAL); } dialogStage.initStyle(StageStyle.UTILITY); dialogStage.setResizable(true); dialogStage.setScene(new Scene(lookupWindow)); dialogStage.getIcons().add(new Image( LookupFieldController.class.getResourceAsStream("/com/panemu/tiwulfx/res/image/lookup.png"))); dialogStage.setTitle(getWindowTitle()); dialogStage.getScene().getStylesheets() .add(getClass().getResource("/com/panemu/tiwulfx/res/tiwulfx.css").toExternalForm()); initCallback(lookupWindow, lookupWindow.table); } for (TableColumn column : lookupWindow.table.getTableView().getColumns()) { if (column instanceof BaseColumn && ((BaseColumn) column).getPropertyName().equals(propertyName)) { if (searchCriteria != null && !searchCriteria.isEmpty()) { TableCriteria tc = new TableCriteria(propertyName, TableCriteria.Operator.ilike_anywhere, searchCriteria); ((BaseColumn) column).setTableCriteria(tc); } else { ((BaseColumn) column).setTableCriteria(null); } break; } } selectedValue = initialValue; beforeShowCallback(lookupWindow.table); lookupWindow.table.reloadFirstPage(); if (stage != null) { /** * Since we support multiple monitors, ensure that the stage is * located in the center of parent stage. But we don't know the * dimension of the stage for the calculation, so we defer the * relocation after the stage is actually displayed. */ Runnable runnable = new Runnable() { public void run() { dialogStage.setX(stage.getX() + stage.getWidth() / 2 - dialogStage.getWidth() / 2); dialogStage.setY(stage.getY() + stage.getHeight() / 2 - dialogStage.getHeight() / 2); //set the opacity back to fully opaque dialogStage.setOpacity(1); } }; Platform.runLater(runnable); //set the opacity to 0 to minimize flicker effect dialogStage.setOpacity(0); } dialogStage.showAndWait(); return selectedValue; }