List of usage examples for java.lang Class getFields
@CallerSensitive public Field[] getFields() throws SecurityException
From source file:org.red5.io.amf3.Output.java
/** {@inheritDoc} */ @Override//from www. j av a 2 s . c om protected void writeArbitraryObject(Object object, Serializer serializer) { Class<?> objectClass = object.getClass(); String className = objectClass.getName(); if (className.startsWith("org.red5.compatibility.")) { // Strip compatibility prefix from classname className = className.substring(23); } // If we need to serialize class information... if (!objectClass.isAnnotationPresent(Anonymous.class)) { putString(className); } else { putString(""); } // Store key/value pairs amf3_mode += 1; // Get public field values Map<String, Object> values = new HashMap<String, Object>(); // Iterate thru fields of an object to build "name-value" map from it for (Field field : objectClass.getFields()) { if (field.isAnnotationPresent(DontSerialize.class)) { if (log.isDebugEnabled()) { log.debug("Skipping " + field.getName() + " because its marked with @DontSerialize"); } continue; } else { int modifiers = field.getModifiers(); if (Modifier.isTransient(modifiers)) { log.warn("Using \"transient\" to declare fields not to be serialized is " + "deprecated and will be removed in Red5 0.8, use \"@DontSerialize\" instead."); continue; } } Object value; try { // Get field value value = field.get(object); } catch (IllegalAccessException err) { // Swallow on private and protected properties access exception continue; } // Put field to the map of "name-value" pairs values.put(field.getName(), value); } // Output public values Iterator<Map.Entry<String, Object>> it = values.entrySet().iterator(); // Iterate thru map and write out properties with separators while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); // Write out prop name putString(entry.getKey()); // Write out serializer.serialize(this, entry.getValue()); } amf3_mode -= 1; // Write out end of object marker putString(""); }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private List<Field> getAllFields(Class claz) { List<Field> allFields = new ArrayList<Field>(); allFields.addAll(Arrays.asList(claz.getFields())); allFields.addAll(Arrays.asList(claz.getDeclaredFields())); if (!Object.class.equals(claz.getSuperclass())) { allFields.addAll(getAllFields(claz.getSuperclass())); }/*from www . j a v a 2 s .com*/ return allFields; }
From source file:org.apache.click.service.XmlConfigService.java
/** * Return an array of bindable fields for the given page class based on * the binding mode.//www.j a v a 2s .co m * * @param pageClass the page class * @param mode the binding mode * @return the field array of bindable fields */ private static Field[] getBindablePageFields(Class pageClass, AutoBinding mode) { if (mode == AutoBinding.DEFAULT) { // Get @Bindable fields Map<String, Field> fieldMap = getAnnotatedBindableFields(pageClass); // Add public fields Field[] publicFields = pageClass.getFields(); for (Field field : publicFields) { fieldMap.put(field.getName(), field); } // Copy the field map values into a field list Field[] fieldArray = new Field[fieldMap.size()]; int i = 0; for (Field field : fieldMap.values()) { fieldArray[i++] = field; } return fieldArray; } else if (mode == AutoBinding.ANNOTATION) { Map<String, Field> fieldMap = getAnnotatedBindableFields(pageClass); // Copy the field map values into a field list Field[] fieldArray = new Field[fieldMap.size()]; int i = 0; for (Field field : fieldMap.values()) { fieldArray[i++] = field; } return fieldArray; } else { return new Field[0]; } }
From source file:weave.servlets.WeaveServlet.java
/** * Tries to convert value to the given type. * @param value The value to cast to a new type. * @param type The desired type./*from w w w . java 2s .c om*/ * @return The value, which may have been cast as the new type. */ protected Object cast(Object value, Class<?> type) throws RemoteException { if (type.isInstance(value)) return value; try { if (value == null) // null -> NaN { if (type == double.class || type == Double.class) value = Double.NaN; else if (type == float.class || type == Float.class) value = Float.NaN; return value; } if (value instanceof Map) // Map -> Java Bean { Object bean = type.newInstance(); for (Field field : type.getFields()) { Object fieldValue = ((Map<?, ?>) value).get(field.getName()); fieldValue = cast(fieldValue, field.getType()); field.set(bean, fieldValue); } return bean; } if (type.isArray()) // ? -> T[] { if (value instanceof String) // String -> String[] value = CSVParser.defaultParser.parseCSVRow((String) value, true); if (value instanceof List) // List -> Object[] value = ((List<?>) value).toArray(); if (value.getClass().isArray()) // T1[] -> T2[] { int n = Array.getLength(value); Class<?> itemType = type.getComponentType(); Object output = Array.newInstance(itemType, n); while (n-- > 0) Array.set(output, n, cast(Array.get(value, n), itemType)); return output; } } if (Collection.class.isAssignableFrom(type)) // ? -> <? extends Collection> { value = cast(value, Object[].class); // ? -> Object[] if (value.getClass().isArray()) // T1[] -> Vector<T2> { int n = Array.getLength(value); List<Object> output = new Vector<Object>(n); TypeVariable<?>[] itemTypes = type.getTypeParameters(); Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null; while (n-- > 0) { Object item = Array.get(value, n); if (itemType != null) item = cast(item, itemType); // T1 -> T2 output.set(n, item); } return output; } } if (value instanceof String) // String -> ? { String string = (String) value; // String -> primitive if (type == char.class || type == Character.class) return string.charAt(0); if (type == byte.class || type == Byte.class) return Byte.parseByte(string); if (type == long.class || type == Long.class) return Long.parseLong(string); if (type == int.class || type == Integer.class) return Integer.parseInt(string); if (type == short.class || type == Short.class) return Short.parseShort(string); if (type == float.class || type == Float.class) return Float.parseFloat(string); if (type == double.class || type == Double.class) return Double.parseDouble(string); if (type == boolean.class || type == Boolean.class) return string.equalsIgnoreCase("true"); if (type == InputStream.class) // String -> InputStream { try { return new ByteArrayInputStream(string.getBytes("UTF-8")); } catch (Exception e) { return null; } } } if (value instanceof Number) // Number -> primitive { Number number = (Number) value; if (type == byte.class || type == Byte.class) return number.byteValue(); if (type == long.class || type == Long.class) return number.longValue(); if (type == int.class || type == Integer.class) return number.intValue(); if (type == short.class || type == Short.class) return number.shortValue(); if (type == float.class || type == Float.class) return number.floatValue(); if (type == double.class || type == Double.class) return number.doubleValue(); if (type == char.class || type == Character.class) return Character.toChars(number.intValue())[0]; if (type == boolean.class || type == Boolean.class) return !Double.isNaN(number.doubleValue()) && number.intValue() != 0; } } catch (Exception e) { throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(), type.getSimpleName()), e); } // Return original value if not handled above. // Primitives and their Object equivalents will cast automatically. return value; }
From source file:com.github.kongchen.swagger.docgen.mavenplugin.SpringMavenDocumentSource.java
private Map<String, SpringResource> analyzeController(Class<?> clazz, Map<String, SpringResource> resourceMap, String description) throws ClassNotFoundException { for (int i = 0; i < clazz.getAnnotation(RequestMapping.class).value().length; i++) { String controllerMapping = clazz.getAnnotation(RequestMapping.class).value()[i]; String resourceName = Utils.parseResourceName(clazz); for (Method m : clazz.getMethods()) { if (m.isAnnotationPresent(RequestMapping.class)) { RequestMapping methodReq = m.getAnnotation(RequestMapping.class); if (methodReq.value() == null || methodReq.value().length == 0 || Utils.parseResourceName(methodReq.value()[0]).equals("")) { if (resourceName.length() != 0) { String resourceKey = Utils.createResourceKey(resourceName, Utils.parseVersion(controllerMapping)); if ((!(resourceMap.containsKey(resourceKey)))) { resourceMap.put(resourceKey, new SpringResource(clazz, resourceName, resourceKey, description)); }/*from ww w. ja v a2 s . co m*/ resourceMap.get(resourceKey).addMethod(m); } } } } } clazz.getFields(); clazz.getDeclaredFields(); //<--In case developer declares a field without an associated getter/setter. //this will allow NoClassDefFoundError to be caught before it triggers bamboo failure. return resourceMap; }
From source file:org.omnaest.utils.beans.BeanUtils.java
/** * Returns a map of property names and {@link BeanPropertyAccessor} instances for all Java Bean properties of the given * {@link Class}. The properties are in no order. * /* w ww .java 2s. c o m*/ * @see #beanPropertyAccessorSet(Class) * @param beanClass * @return */ @SuppressWarnings("unchecked") public static <B> Map<String, BeanPropertyAccessor<B>> propertyNameToBeanPropertyAccessorMap( Class<B> beanClass) { // Map<String, BeanPropertyAccessor<B>> retmap = new HashMap<String, BeanPropertyAccessor<B>>(); // if (beanClass != null) { // try { // MapElementMergeOperation<String, BeanPropertyAccessor<B>> mapElementMergeOperation = new MapElementMergeOperation<String, BeanPropertyAccessor<B>>() { @Override public void merge(String key, BeanPropertyAccessor<B> value, Map<String, BeanPropertyAccessor<B>> mergedMap) { // if (mergedMap.containsKey(key)) { BeanPropertyAccessor<B> beanPropertyAccessor = mergedMap.get(key); BeanPropertyAccessor<B> beanPropertyAccessorMerged = BeanPropertyAccessor .merge(beanPropertyAccessor, value); mergedMap.put(key, beanPropertyAccessorMerged); } else { mergedMap.put(key, value); } } }; retmap = MapUtils.mergeAll(mapElementMergeOperation, BeanUtils.propertyNameToBeanPropertyAccessorMap(beanClass, beanClass.getDeclaredFields()), BeanUtils.propertyNameToBeanPropertyAccessorMap(beanClass, beanClass.getDeclaredMethods()), BeanUtils.propertyNameToBeanPropertyAccessorMap(beanClass, beanClass.getFields()), BeanUtils.propertyNameToBeanPropertyAccessorMap(beanClass, beanClass.getMethods())); } catch (Exception e) { } } // return retmap; }
From source file:org.ebayopensource.turmeric.tools.errorlibrary.ErrorLibraryFileGenerationTest.java
public void assertErrorConstants(File srcDir, ExpectedErrors expectedErrors) throws Exception { String classname = expectedErrors.expectedPackageName + ".ErrorConstants"; File javaFile = CodeGenAssert.assertJavaSourceExists(srcDir, classname); compileJavaFiles(srcDir, javaFile);//from ww w . j av a2 s .c om Class<?> actualClass = loadTestProjectClass(classname, srcDir); CodeGenAssert.assertClassPackage(actualClass, expectedErrors.expectedPackageName); CodeGenAssert.assertClassName(actualClass, "ErrorConstants"); CodeGenAssert.assertClassIsPublic(actualClass); // To store found field names for later assertion. List<String> fieldnames = new ArrayList<String>(); // Walk fields for (Field f : actualClass.getFields()) { String fieldname = f.getName(); CodeGenAssert.assertFieldIsPublicStaticFinal(f); if (fieldname.equals("ERRORDOMAIN")) { CodeGenAssert.assertFieldType(f, String.class); String value = (String) f.get(null); Assert.assertThat("ERRORDOMAIN", value, is(expectedErrors.expectedErrorDomain)); continue; } fieldnames.add(fieldname); expectedErrors.assertErrorMessageExists(fieldname); } // Validate that all expected fields exist. for (CommonErrorData expected : expectedErrors.getExpectedErrors()) { String expectedName = expected.getErrorName().toLowerCase(); Assert.assertThat("Expected field exists: " + expectedName, fieldnames, hasItem(expectedName.toUpperCase())); } Assert.assertThat("Field Count", fieldnames.size(), is(expectedErrors.getCount())); }
From source file:org.ebayopensource.turmeric.tools.errorlibrary.ErrorLibraryFileGenerationTest.java
public void assertErrorDataCollection(File srcDir, ExpectedErrors expectedErrors) throws Exception { String classname = expectedErrors.expectedPackageName + ".ErrorDataCollection"; File javaFile = CodeGenAssert.assertJavaSourceExists(srcDir, classname); compileJavaFiles(srcDir, javaFile);//ww w .j a v a2 s .co m Class<?> actualClass = loadTestProjectClass(classname, srcDir); CodeGenAssert.assertClassPackage(actualClass, expectedErrors.expectedPackageName); CodeGenAssert.assertClassName(actualClass, "ErrorDataCollection"); CodeGenAssert.assertClassIsPublic(actualClass); // To store found fields for later assertion. Map<String, CommonErrorData> fields = new HashMap<String, CommonErrorData>(); // Walk fields for (Field f : actualClass.getFields()) { String fieldname = f.getName(); if (fieldname.equals("ORGANIZATION")) { CodeGenAssert.assertFieldIsPrivateStaticFinal(f); CodeGenAssert.assertFieldType(f, String.class); f.setAccessible(true); // its private after all String value = (String) f.get(null); Assert.assertThat("ORGANIZATION", value, is(expectedErrors.expectedOrganization)); continue; } CodeGenAssert.assertFieldIsPublicStaticFinal(f); if (CommonErrorData.class.isAssignableFrom(f.getType())) { CommonErrorData ced = (CommonErrorData) f.get(null); fields.put(fieldname, ced); expectedErrors.assertErrorMessageExists(fieldname); } } // Validate that all expected fields exist. for (CommonErrorData expected : expectedErrors.getExpectedErrors()) { String expectedName = expected.getErrorName().toLowerCase(); Assert.assertThat("Expected field exists: " + expectedName, fields.keySet(), hasItem(expectedName)); CommonErrorData actualError = fields.get(expectedName); Assert.assertNotNull("Actual CommonErrorData found in class", actualError); Assert.assertThat("CommonErrorData.errorId", actualError.getErrorId(), is(expected.getErrorId())); Assert.assertThat("CommonErrorData.errorName", actualError.getErrorName(), is(expected.getErrorName())); Assert.assertThat("CommonErrorData.severity", actualError.getSeverity(), is(expected.getSeverity())); Assert.assertThat("CommonErrorData.category", actualError.getCategory(), is(expected.getCategory())); Assert.assertThat("CommonErrorData.domain", actualError.getDomain(), is(expected.getDomain())); Assert.assertThat("CommonErrorData.subdomain", actualError.getSubdomain(), is(expected.getSubdomain())); Assert.assertThat("CommonErrorData.errorGroups", actualError.getErrorGroups(), is(expected.getErrorGroups())); } Assert.assertThat("Field Count", fields.size(), is(expectedErrors.getCount())); }
From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java
private int countFieldsInClass(Class<?> clazz) { int fieldCount = 0; for (Field field : clazz.getFields()) { // get all fields if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) { fieldCount++;/*from ww w . j a v a2 s .c o m*/ } } return fieldCount; }
From source file:org.jakz.common.JSONObject.java
private void populateFromPOJO(Object pojo) throws IllegalArgumentException, IllegalAccessException { Class<?> pojoClass = pojo.getClass(); Field[] field = pojoClass.getFields(); for (int i = 0; i < field.length; i++) { String fieldName = field[i].getName(); Object fieldValue = null; //try//from w ww . j a v a 2 s .c om //{ fieldValue = field[i].get(pojo); //} //catch (Exception e) //{ //ignore this member //} put(fieldName, wrap(fieldValue)); } }