List of usage examples for java.lang.reflect Field getName
public String getName()
From source file:com.alibaba.fastjson.parser.ParserConfig.java
/** * fieldName,field ?fieldName??findField * //from ww w .j ava2 s . c o m * @param clazz * @param fieldCacheMap :map<fieldName ,Field> */ public static void parserAllFieldToCache(Class<?> clazz, Map</**fieldName*/ String, Field> fieldCacheMap) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); if (!fieldCacheMap.containsKey(fieldName)) { fieldCacheMap.put(fieldName, field); } } if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) { parserAllFieldToCache(clazz.getSuperclass(), fieldCacheMap); } }
From source file:io.siddhi.doc.gen.core.utils.DocumentationUtils.java
/** * Generate a file from a template/* w w w .j a va 2 s .c o m*/ * * @param templateFile The template file name * @param dataModel The data model to be used for generating the output files from template files * @param outputDirectory The output directory in which the file will be generated * @param outputFileName The name of the file that will be generated * @throws MojoFailureException if the Mojo fails to find template file or create new documentation file */ private static void generateFileFromTemplate(String templateFile, Map<String, Object> dataModel, String outputDirectory, String outputFileName) throws MojoFailureException { // Creating the free marker configuration Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setClassForTemplateLoading(DocumentationUtils.class, File.separator + Constants.TEMPLATES_DIRECTORY); // Adding the constants to the freemarker data model Map<String, String> constantsClassFieldMap = new HashMap<>(); for (Field field : Constants.class.getDeclaredFields()) { try { constantsClassFieldMap.put(field.getName(), field.get(null).toString()); } catch (IllegalAccessException ignored) { // Ignoring inaccessible variables } } dataModel.put("CONSTANTS", constantsClassFieldMap); // Adding the ExtensionType enum values to the freemarker data model Map<String, String> extensionTypeEnumMap = new HashMap<>(); for (Field field : ExtensionType.class.getDeclaredFields()) { try { if (field.isEnumConstant()) { extensionTypeEnumMap.put(field.getName(), ((ExtensionType) field.get(null)).getValue()); } } catch (IllegalAccessException ignored) { // Ignoring inaccessible variables } } dataModel.put("EXTENSION_TYPE", extensionTypeEnumMap); try { // Fetching the template Template template = cfg.getTemplate(templateFile); // Generating empty documentation files File outputFile = new File(outputDirectory + File.separator + outputFileName); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { throw new MojoFailureException("Unable to create directory " + outputFile.getParentFile()); } } if (!outputFile.exists()) { if (!outputFile.createNewFile()) { throw new MojoFailureException("Unable to create file " + outputFile.getAbsolutePath()); } } // Writing to the documentation file try (OutputStream outputStream = new FileOutputStream(outputFile)) { try (Writer writer = new OutputStreamWriter(outputStream, Charset.defaultCharset())) { template.process(dataModel, writer); } } catch (TemplateException e) { throw new MojoFailureException("Invalid Free Marker template found in " + templateFile, e); } } catch (IOException e) { throw new MojoFailureException("Unable to find template file " + templateFile, e); } }
From source file:gov.nih.nci.system.web.util.RESTUtil.java
/** * Convert ISO attr parts into attribute names Expected formats: List< Map< * String, List<?> > > ? can be String or a Map<String, String> * [{part_0=[value, code, codeSystem, {type=[AL]}]}, {part_1=[value, code, * codeSystem, {type=[AL]}]}] resulting: part_0.value, part_0.code, * part_0.codeSystem, part_0.type, part_1.value, part_1.code, * part_1.codeSystem, part_1.type//from www . j a v a 2 s . c o m * * Expected formats: List< Map< String, List< Map< String, List<?> > > > > ? * can be String or a Map<String, String> * [{item<gov.nih.nci.iso21090.Ad>=[{part_0=[value, code, codeSystem, * {type=[AL]}]}, {part_1=[value, code, codeSystem, {type=[AL]}]}]}] * resulting: item.part_0.value, item.part_0.code, item.part_0.codeSystem, * item.part_0.type, item.part_1.value, item.part_1.code, * item.part_1.codeSystem, item.part_1.type * * * @param attrs * @return */ public static List<String> getSearchableIsoDataTypeFieldsForCd(Field field, List attrs) { String typeName = field.getType().getName(); String fieldName = field.getName(); List<String> fnAttrs = new ArrayList(); // List of ISO fields Iterator iter = attrs.iterator(); while (iter.hasNext()) { Object obj = iter.next(); if (obj instanceof java.lang.String) { String value = (String) obj; if (field.getName().equals(value)) fnAttrs.add(value); else fnAttrs.add(field.getName() + "." + value); // log.debug("instanceof java.lang.String*******" + // obj); } else if (obj instanceof java.util.Map) { Map valueMap = (java.util.Map) obj; Iterator valueIter = valueMap.keySet().iterator(); while (valueIter.hasNext()) { String key = (String) valueIter.next(); List keyValues = (java.util.List) valueMap.get(key); Iterator listIter = keyValues.iterator(); while (listIter.hasNext()) { String keyValueName = (String) listIter.next(); fnAttrs.add(field.getName() + "." + key + "." + keyValueName); } } // log.debug("Don't know-----------------------"); } } // log.debug("returning fnAttrs: " + fnAttrs); return fnAttrs; }
From source file:adalid.core.XS1.java
static boolean checkFieldAnnotation(boolean log, Field field, Class<? extends Annotation> annotation, Class<?>[] validTypes) { String name = field.getName(); Class<?> type = field.getDeclaringClass(); String string;// ww w . jav a 2 s . com int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) { string = "field " + name + " has static and/or final modifier"; if (log) { logFieldAnnotationErrorMessage(name, type, annotation, string); } return false; } int length = validTypes == null ? 0 : validTypes.length; if (length < 1) { return true; } Class<?> ft = getTrueType(field.getType()); String[] strings = new String[length]; int i = 0; for (Class<?> vt : validTypes) { if (vt.isAssignableFrom(ft)) { return true; } strings[i++] = vt.getSimpleName(); } string = "type of " + name + " is not " + StringUtils.join(strings, " or "); if (log) { logFieldAnnotationErrorMessage(name, type, annotation, string); } return false; }
From source file:jp.co.golorp.emarf.model.Models.java
/** * ??????????//from w w w . ja v a 2s. c o m * * @param <T> * * @param bean * ??bean */ private static <T> void cp2org(final T bean) { Class<?> clazz = bean.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getName().startsWith(BeanGenerator.ORG_PREFIX)) { try { String orgName = field.getName(); String propertyName = orgName.replaceFirst(BeanGenerator.ORG_PREFIX, ""); Field property = clazz.getDeclaredField(propertyName); field.setAccessible(true); property.setAccessible(true); Object value = property.get(bean); field.set(bean, value); } catch (Exception e) { throw new SystemError(e); } } } }
From source file:com.shenit.commons.utils.GsonUtils.java
/** * ???./* w ww .ja va2 s . c om*/ * @param clazz * @return */ public static Field<?>[] serializeFields(Class<?> clazz) { if (REGISTERED_FIELDS.containsKey(clazz)) return REGISTERED_FIELDS.get(clazz); java.lang.reflect.Field[] fields = clazz.getDeclaredFields(); List<Field<?>> fs = Lists.newArrayList(); SerializedName serializedName; JsonProperty jsonProp; IgnoreField ignore; for (java.lang.reflect.Field field : fields) { if (field == null) continue; serializedName = field.getAnnotation(SerializedName.class); jsonProp = field.getAnnotation(JsonProperty.class); ignore = field.getAnnotation(IgnoreField.class); if (ignore != null) continue; String name = null; if (serializedName != null) { name = serializedName.value(); } else if (jsonProp != null) { name = jsonProp.value(); } else { name = Modifier.isStatic(field.getModifiers()) ? null : field.getName(); } if (name == null) continue; Default defVal = field.getDeclaredAnnotation(Default.class); fs.add(new Field(name, field.getName(), field.getType(), defVal == null ? null : defVal.value())); } Field<?>[] fsArray = fs.toArray(new Field<?>[0]); REGISTERED_FIELDS.put(clazz, fsArray); return fsArray; }
From source file:cn.aposoft.util.spring.ReflectionUtils.java
/** * Attempt to find a {@link Field field} on the supplied {@link Class} with * the supplied {@code name} and/or {@link Class type}. Searches all * superclasses up to {@link Object}.//from w ww .j ava 2 s .co m * * @param clazz * the class to introspect * @param name * the name of the field (may be {@code null} if type is * specified) * @param type * the type of the field (may be {@code null} if name is * specified) * @return the corresponding Field object, or {@code null} if not found */ public static Field findField(Class<?> clazz, String name, Class<?> type) { Assert.notNull(clazz, "Class must not be null"); Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified"); Class<?> searchType = clazz; while (Object.class != searchType && searchType != null) { Field[] fields = getDeclaredFields(searchType); for (Field field : fields) { if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) { return field; } } searchType = searchType.getSuperclass(); } return null; }
From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java
public static Map<String, Object> getBXMLFieldValues(Bindable obj) throws IllegalAccessException { Map<String, Object> result = new HashMap<>(); Class<?> type = obj.getClass(); Field[] allFields = FieldUtils.getAllFields(type); if (ArrayUtils.isNotEmpty(allFields)) { for (Field field : allFields) { BXML bxmlAnnotation = field.getAnnotation(BXML.class); if (bxmlAnnotation != null) { String id = bxmlAnnotation.id(); Object fieldValue = FieldUtils.readField(field, obj, true); if (StringUtils.isNotBlank(id)) { result.put(id, fieldValue); } else { result.put(field.getName(), fieldValue); }/*from w w w . jav a2 s .c o m*/ } } } return result; }
From source file:HashCodeAssist.java
/** * <p>//from w ww.j a v a 2 s . c o m * Appends the fields and values defined by the given object of the given * <code>Class</code>. * </p> * * @param object * the object to append details of * @param clazz * the class to append details of * @param builder * the builder to append to * @param useTransients * whether to use transient fields * @param excludeFields * Collection of String field names to exclude from use in * calculation of hash code */ private static void reflectionAppend(Object object, Class<?> clazz, HashCodeAssist builder, boolean useTransients, String... excludeFields) { if (isRegistered(object)) { return; } try { register(object); Field[] fields = clazz.getDeclaredFields(); List<String> excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST; AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (!excludedFieldList.contains(field.getName()) && (field.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(field.getModifiers())) && (!Modifier.isStatic(field.getModifiers()))) { try { Object fieldValue = field.get(object); builder.append(fieldValue); } catch (IllegalAccessException e) { // this can't happen. Would get a Security exception // instead // throw a runtime exception in case the impossible // happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } finally { unregister(object); } }
From source file:app.core.PersistenceTest.java
private static <T extends PersistentObject> T buildRecursively(T newInstance) throws Exception { Set<ConstraintViolation<T>> constraintViolations = validate(newInstance); if (constraintViolations.isEmpty()) return newInstance; // the instance is finished building for (ConstraintViolation constraintViolation : constraintViolations) { Object missingProperty;// ww w.ja v a 2 s .co m Field violatedField = ReflectionUtils.getField(constraintViolation.getRootBeanClass(), constraintViolation.getPropertyPath().toString()); if (NotNull.class .isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) { if (PersistentObject.class.isAssignableFrom(violatedField.getType())) { // similar to instanceof missingProperty = newInstance((Class<PersistentObject>) violatedField.getType()); //recursion here ((PersistentObject) missingProperty).save(); // save the dependency } else { missingProperty = violatedField.getType().newInstance(); // just create a non-null property } ReflectionUtils.setFieldValue(newInstance, violatedField.getName(), missingProperty); } else if (Length.class .isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) { // TODO: implement correctly ReflectionUtils.setFieldValue(newInstance, violatedField.getName(), "0123456789"); } // TODO: support more annotations } return buildRecursively(newInstance); }