List of usage examples for java.lang.reflect Field getDeclaringClass
@Override
public Class<?> getDeclaringClass()
From source file:org.tdar.core.service.ReflectionService.java
/** * Based on the field and the object passed in, call the getter and return the result * //from w w w. ja va 2 s .c o m * @param obj * @param field * @return */ @SuppressWarnings("unchecked") public <T> T callFieldGetter(Object obj, Field field) { // logger.debug("calling getter on: {} {} ", obj, field.getName()); logger.trace("{}", field.getDeclaringClass()); Method method = ReflectionUtils.findMethod(field.getDeclaringClass(), generateGetterName(field)); if (method.getReturnType() != Void.TYPE) { try { return (T) method.invoke(obj); } catch (Exception e) { logger.debug("cannot call field getter for field: {}", field, e); } } return null; }
From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java
private byte[] columnFamilyNameFromHBaseObjectFieldAnnotatedField(final Field hbaseMapFieldAnnotatedField) { return hbaseMapFieldAnnotatedField.getAnnotation(HBaseObjectField.class).columnFamilyName().isEmpty() ? defaultColumnFamilyNameFrom(hbaseMapFieldAnnotatedField.getDeclaringClass()) : Bytes.toBytes(//from w w w .jav a 2 s . c o m hbaseMapFieldAnnotatedField.getAnnotation(HBaseObjectField.class).columnFamilyName()); }
From source file:org.evosuite.testcase.ImportsTestCodeVisitor.java
/** * <p>//from w ww . j a v a 2 s .c om * visitPrimitiveFieldAssertion * </p> * * @param assertion * a {@link PrimitiveFieldAssertion} * object. */ protected void visitPrimitiveFieldAssertion(PrimitiveFieldAssertion assertion) { VariableReference source = assertion.getSource(); Object value = assertion.getValue(); Field field = assertion.getField(); if (Modifier.isStatic(field.getModifiers())) { getClassName(field.getDeclaringClass()); } else { getClassName(source); } if (value != null && value.getClass().isEnum()) { // Make sure the enum is imported in the JUnit test getClassName(value.getClass()); } }
From source file:acmi.l2.clientmod.xdat.Controller.java
private static void buildTree(IOEntity entity, Field listField, TreeView<Object> elements, String nameFilter) { elements.setRoot(null);//from w ww . j a v a2 s .com if (entity == null) return; try { List<IOEntity> list = (List<IOEntity>) listField.get(entity); if (!listField.isAnnotationPresent(Type.class)) { log.log(Level.WARNING, String.format("XDAT.%s: @Type not defined", listField.getName())); Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null, String.format("XDAT.%s: @Type not defined", listField.getName())); } else { Class<? extends IOEntity> type = listField.getAnnotation(Type.class).value() .asSubclass(IOEntity.class); TreeItem<Object> rootItem = new TreeItem<>(new ListHolder(entity, list, listField.getName(), type)); elements.setRoot(rootItem); rootItem.getChildren().addAll(list.stream().map(Controller::createTreeItem) .filter(treeItem -> checkTreeNode(treeItem, nameFilter)).collect(Collectors.toList())); } } catch (IllegalAccessException e) { log.log(Level.WARNING, String.format("%s.%s is not accessible", listField.getDeclaringClass().getSimpleName(), listField.getName()), e); Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null, listField.getDeclaringClass().getSimpleName() + "." + listField.getName() + " is not accessible"); } }
From source file:com.adaptris.core.marshaller.xstream.AliasedElementReflectionConverter.java
protected void doMarshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) { final List<FieldInfo> fields = new ArrayList<>(); final Map<String, java.lang.reflect.Field> defaultFieldDefinition = new HashMap<>(); // Attributes might be preferred to child elements ... reflectionProvider.visitSerializableFields(source, new ReflectionProvider.Visitor() { final Set<String> writtenAttributes = new HashSet<>(); public void visit(String fieldName, Class type, Class definedIn, Object value) { if (!mapper.shouldSerializeMember(definedIn, fieldName)) { return; }//from www .j a v a2 s . c o m if (!defaultFieldDefinition.containsKey(fieldName)) { Class lookupType = source.getClass(); // See XSTR-457 and OmitFieldsTest if (definedIn != source.getClass() && !mapper.shouldSerializeMember(lookupType, fieldName)) { lookupType = definedIn; } defaultFieldDefinition.put(fieldName, reflectionProvider.getField(lookupType, fieldName)); } SingleValueConverter converter = mapper.getConverterFromItemType(fieldName, type, definedIn); if (converter != null) { final String attribute = mapper .aliasForAttribute(mapper.serializedMember(definedIn, fieldName)); if (value != null) { if (writtenAttributes.contains(fieldName)) { // TODO: use attribute throw new ConversionException("Cannot write field with name '" + fieldName + "' twice as attribute for object of type " + source.getClass().getName()); } final String str = converter.toString(value); if (str != null) { writer.addAttribute(attribute, str); } } writtenAttributes.add(fieldName); // TODO: use attribute } else { fields.add(new FieldInfo(fieldName, type, definedIn, value)); } } }); new Object() { { for (Iterator<FieldInfo> fieldIter = fields.iterator(); fieldIter.hasNext();) { FieldInfo info = (FieldInfo) fieldIter.next(); // Check if the field is not null, we don't output null fields if (info.value != null) { Mapper.ImplicitCollectionMapping mapping = mapper .getImplicitCollectionDefForFieldName(source.getClass(), info.fieldName); if (mapping != null) { if (context instanceof ReferencingMarshallingContext) { if (info.value != Collections.EMPTY_LIST && info.value != Collections.EMPTY_SET && info.value != Collections.EMPTY_MAP) { ReferencingMarshallingContext refContext = (ReferencingMarshallingContext) context; refContext.registerImplicit(info.value); } } final boolean isCollection = info.value instanceof Collection; final boolean isMap = info.value instanceof Map; final boolean isEntry = isMap && mapping.getKeyFieldName() == null; final boolean isArray = info.value.getClass().isArray(); for (Iterator iter = isArray ? new ArrayIterator(info.value) : isCollection ? ((Collection) info.value).iterator() : isEntry ? ((Map) info.value).entrySet().iterator() : ((Map) info.value).values().iterator(); iter.hasNext();) { Object obj = iter.next(); final String itemName; final Class itemType; if (obj == null) { itemType = Object.class; itemName = mapper.serializedClass(null); } else if (isEntry) { final String entryName = mapping.getItemFieldName() != null ? mapping.getItemFieldName() : mapper.serializedClass(Map.Entry.class); Map.Entry entry = (Map.Entry) obj; ExtendedHierarchicalStreamWriterHelper.startNode(writer, entryName, entry.getClass()); writeItem(entry.getKey(), context, writer); writeItem(entry.getValue(), context, writer); writer.endNode(); continue; } else if (mapping.getItemFieldName() != null) { itemType = mapping.getItemType(); itemName = mapping.getItemFieldName(); } else { itemType = obj.getClass(); itemName = mapper.serializedClass(itemType); } writeField(info.fieldName, itemName, itemType, info.definedIn, obj); } } // Field is not an implicit collection else { writeField(info.fieldName, null, info.type, info.definedIn, info.value); } } } } // void writeFieldStandard(String fieldName, String aliasName, Class fieldType, Class definedIn, Object newObj) { // Class actualType = newObj != null ? newObj.getClass() : fieldType; // ExtendedHierarchicalStreamWriterHelper.startNode( // writer, // aliasName != null ? aliasName : mapper.serializedMember( // source.getClass(), fieldName), actualType); // // // We don't process null fields (field values) // if (newObj != null) { // Class defaultType = mapper.defaultImplementationOf(fieldType); // if (!actualType.equals(defaultType)) { // String serializedClassName = mapper.serializedClass(actualType); // if (!serializedClassName // .equals(mapper.serializedClass(defaultType))) { // String attributeName = mapper.aliasForSystemAttribute("class"); // if (attributeName != null) { // writer.addAttribute(attributeName, serializedClassName); // } // } // } // // final Field defaultField = (Field) defaultFieldDefinition // .get(fieldName); // if (defaultField.getDeclaringClass() != definedIn) { // String attributeName = mapper.aliasForSystemAttribute("defined-in"); // if (attributeName != null) { // writer.addAttribute(attributeName, // mapper.serializedClass(definedIn)); // } // } // // Field field = reflectionProvider.getField(definedIn, fieldName); // marshallField(context, newObj, field); // } // writer.endNode(); // } // Modified version of method from that super class void writeField(String fieldName, String aliasName, Class fieldType, Class definedIn, Object newObj) { Class<?> actualType = newObj != null ? newObj.getClass() : fieldType; String elementName = aliasName != null ? aliasName : mapper.serializedMember(source.getClass(), fieldName); String classAttributeName = null; String definedAttributeName = null; // We don't process null fields (field values) if (newObj != null) { Class defaultType = mapper.defaultImplementationOf(fieldType); if (!actualType.equals(defaultType)) { String serializedClassName = mapper.serializedClass(actualType); if (!serializedClassName.equals(mapper.serializedClass(defaultType))) { classAttributeName = mapper.aliasForSystemAttribute("class"); } } final Field defaultField = (Field) defaultFieldDefinition.get(fieldName); if (defaultField.getDeclaringClass() != definedIn) { definedAttributeName = mapper.aliasForSystemAttribute("defined-in"); } } writeOutElementBasedOnClassType(elementName, definedIn, actualType, classAttributeName, definedAttributeName); if (newObj != null) { Field field = reflectionProvider.getField(definedIn, fieldName); marshallField(context, newObj, field); } writer.endNode(); } // Now where the super class would have written out the field name // followed by a class attribute that contained the subclass name, // we will write out the subclass alias name as the element with no // class attribute at all. private void writeOutElementBasedOnClassType(String elementName, Class definedIn, Class<?> actualType, String classAttributeName, String definedAttributeName) { boolean isClassAttributeSet = !StringUtils.isBlank(classAttributeName); if (isClassAttributeSet) { String serializedClassName = mapper.serializedClass(actualType); ExtendedHierarchicalStreamWriterHelper.startNode(writer, serializedClassName, actualType); } else { String serializedClassName = mapper.serializedClass(actualType); ExtendedHierarchicalStreamWriterHelper.startNode(writer, elementName, actualType); if (classAttributeName != null) { writer.addAttribute(classAttributeName, serializedClassName); } if (definedAttributeName != null) { writer.addAttribute(definedAttributeName, mapper.serializedClass(definedIn)); } } } void writeItem(Object item, MarshallingContext context, HierarchicalStreamWriter writer) { if (item == null) { String name = mapper.serializedClass(null); ExtendedHierarchicalStreamWriterHelper.startNode(writer, name, Mapper.Null.class); writer.endNode(); } else { String name = mapper.serializedClass(item.getClass()); ExtendedHierarchicalStreamWriterHelper.startNode(writer, name, item.getClass()); context.convertAnother(item); writer.endNode(); } } }; }
From source file:com.adaptris.core.marshaller.xstream.AliasedElementReflectionConverter.java
/** * Unmarshall the XML data from the reader and create the object instance. *///from w ww.j a va 2 s . c om @Override public Object doUnmarshal(final Object result, final HierarchicalStreamReader reader, final UnmarshallingContext context) { final Class resultType = result.getClass(); final Set<FastField> seenFields = new HashSet() { public boolean add(Object e) { if (!super.add(e)) { throw new DuplicateFieldException(((FastField) e).getName()); } return true; } }; // process attributes before recursing into child elements. Iterator<?> it = reader.getAttributeNames(); while (it.hasNext()) { String attrAlias = (String) it.next(); // TODO: realMember should return FastField String attrName = mapper.realMember(resultType, mapper.attributeForAlias(attrAlias)); Field field = reflectionProvider.getFieldOrNull(resultType, attrName); if (field != null && shouldUnmarshalField(field)) { Class classDefiningField = field.getDeclaringClass(); if (!mapper.shouldSerializeMember(classDefiningField, attrName)) { continue; } // we need a converter that produces a string representation only SingleValueConverter converter = mapper.getConverterFromAttribute(classDefiningField, attrName, field.getType()); Class type = field.getType(); if (converter != null) { Object value = converter.fromString(reader.getAttribute(attrAlias)); if (type.isPrimitive()) { type = Primitives.box(type); } if (value != null && !type.isAssignableFrom(value.getClass())) { throw new ConversionException( "Cannot convert type " + value.getClass().getName() + " to type " + type.getName()); } seenFields.add(new FastField(classDefiningField, attrName)); reflectionProvider.writeField(result, attrName, value, classDefiningField); } } } Map implicitCollectionsForCurrentObject = null; // Process the child nodes of the current node while (reader.hasMoreChildren()) { boolean validMatchFound = false; reader.moveDown(); String originalNodeName = reader.getNodeName(); log.trace("Reading processing node: {}", originalNodeName); Class explicitDeclaringClass = readDeclaringClass(reader); Class fieldDeclaringClass = explicitDeclaringClass == null ? resultType : explicitDeclaringClass; String fieldName = mapper.realMember(fieldDeclaringClass, originalNodeName); Mapper.ImplicitCollectionMapping implicitCollectionMapping = mapper .getImplicitCollectionDefForFieldName(fieldDeclaringClass, fieldName); final Object value; String implicitFieldName = null; Field field = null; Class type = null; // Handle standard field ie one not marked as implicit if (implicitCollectionMapping == null) { // no item of an implicit collection for this name ... do we have a // field? field = reflectionProvider.getFieldOrNull(fieldDeclaringClass, fieldName); if (field == null) { // it is not a field ... do we have a field alias? Class itemType = mapper.getItemTypeForItemFieldName(resultType, fieldName); if (itemType != null) { String classAttribute = HierarchicalStreams.readClassAttribute(reader, mapper); if (classAttribute != null) { type = mapper.realClass(classAttribute); } else { type = itemType; } } else { // it is not an alias ... do we have an element of an implicit // collection based on type only? try { type = mapper.realClass(originalNodeName); implicitFieldName = mapper.getFieldNameForItemTypeAndName(context.getRequiredType(), type, originalNodeName); // If there is an implicit collection with the // itemFieldName set, then we must bypass XStream's // implicit collection matching because it will not // match the subclass name to the itemFieldName! if (implicitFieldName == null) { implicitFieldName = XStreamUtils .getImplicitCollectionFieldNameForType(context.getRequiredType(), type); } } catch (CannotResolveClassException e) { // type stays null ... } if (type == null || implicitFieldName == null) { Field matchedField = XStreamUtils.getMatchedFieldFromClass(resultType, type, seenFields); if (matchedField != null) { field = matchedField; fieldName = matchedField.getName(); validMatchFound = true; } if (!validMatchFound) { // either not a type or element is a type alias, but does not // belong to an implicit field handleUnknownField(explicitDeclaringClass, fieldName, resultType, originalNodeName); // element is unknown in declaring class, ignore it now type = null; } } } if (validMatchFound) { value = unmarshallField(context, result, type, field); // value = reflectionProvider.newInstance(type); // TODO perhaps call // context.convertAnother(result, // type); } else if (type == null) { // no type, no value value = null; } else { if (Map.Entry.class.equals(type)) { // it is an element of an implicit map with two elements now forkey and value reader.moveDown(); final Object key = context.convertAnother(result, HierarchicalStreams.readClassType(reader, mapper)); reader.moveUp(); reader.moveDown(); final Object v = context.convertAnother(result, HierarchicalStreams.readClassType(reader, mapper)); reader.moveUp(); value = Collections.singletonMap(key, v).entrySet().iterator().next(); } else { // recurse info hierarchy value = context.convertAnother(result, type); } } } // Handle valid class field else { boolean fieldAlreadyChecked = false; // we have a field, but do we have to address a hidden one? if (explicitDeclaringClass == null) { while (field != null && !(fieldAlreadyChecked = shouldUnmarshalField(field) && mapper.shouldSerializeMember(field.getDeclaringClass(), fieldName))) { field = reflectionProvider.getFieldOrNull(field.getDeclaringClass().getSuperclass(), fieldName); } } if (field != null && (fieldAlreadyChecked || (shouldUnmarshalField(field) && mapper.shouldSerializeMember(field.getDeclaringClass(), fieldName)))) { String classAttribute = HierarchicalStreams.readClassAttribute(reader, mapper); if (classAttribute != null) log.trace("Reading class attribute: ", classAttribute); if (classAttribute != null) { type = mapper.realClass(classAttribute); } else { type = mapper.defaultImplementationOf(field.getType()); } // TODO the reflection provider should already return the proper field value = unmarshallField(context, result, type, field); Class definedType = field.getType(); if (!definedType.isPrimitive()) { type = definedType; } } else { value = null; } } } // Handle collection field with implicit mapping else { // we have an implicit collection with defined names implicitFieldName = implicitCollectionMapping.getFieldName(); type = implicitCollectionMapping.getItemType(); if (type == null) { String classAttribute = HierarchicalStreams.readClassAttribute(reader, mapper); type = mapper.realClass(classAttribute != null ? classAttribute : originalNodeName); } value = context.convertAnother(result, type); } if (value != null && !type.isAssignableFrom(value.getClass())) { throw new ConversionException( "Cannot convert type " + value.getClass().getName() + " to type " + type.getName()); } if (field != null) { log.trace("Updating field value for field: {}", fieldName); if (validMatchFound) { reflectionProvider.writeField(result, fieldName, value, field.getDeclaringClass()); } else { reflectionProvider.writeField(result, fieldName, value, field.getDeclaringClass()); } seenFields.add(new FastField(field.getDeclaringClass(), fieldName)); } else if (type != null) { if (implicitFieldName == null) { // look for implicit field implicitFieldName = mapper.getFieldNameForItemTypeAndName(context.getRequiredType(), value != null ? value.getClass() : Mapper.Null.class, originalNodeName); } if (implicitCollectionsForCurrentObject == null) { implicitCollectionsForCurrentObject = new HashMap(); } writeValueToImplicitCollection(value, implicitCollectionsForCurrentObject, result, implicitFieldName); } reader.moveUp(); } if (implicitCollectionsForCurrentObject != null) { for (Iterator iter = implicitCollectionsForCurrentObject.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); Object value = entry.getValue(); if (value instanceof ArraysList) { Object array = ((ArraysList) value).toPhysicalArray(); reflectionProvider.writeField(result, (String) entry.getKey(), array, null); } } } return result; }
From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java
/** * Write final static field.// w ww .j a v a 2 s.c o m * * @param field the field * @param value the value */ public static void writeFinalStaticField(Field field, Object value) { AccessibleScope ascope = new AccessibleScope(field); try { Field modifiersField = Field.class.getDeclaredField("modifiers"); AccessibleScope modscope = new AccessibleScope(field); try { int oldmods = field.getModifiers(); modifiersField.setInt(field, oldmods & ~Modifier.FINAL); writeField(null, field, value); modifiersField.setInt(field, oldmods); } finally { modscope.restore(); } } catch (RuntimeException ex) { // NOSONAR "Illegal Catch" framework throw ex; // NOSONAR "Illegal Catch" framework } catch (Exception ex) { // NOSONAR "Illegal Catch" framework throw new RuntimeException( "Cannot write field: " + field.getDeclaringClass().getName() + "." + field.getName());// NOSONAR "Illegal Catch" framework } finally { ascope.restore(); } }
From source file:org.firebrandocm.dao.ClassMetadata.java
/** * Processes metadata for a simple column. Helper method * * @param element the type/*from w w w .j a va 2s .c o m*/ * @param propertyName the property name */ private void processSimpleColumn(Field element, String propertyName) throws ClassNotFoundException, IntrospectionException { propertiesTypesMap.put(propertyName, element.getType()); mutationProperties.add(propertyName); propertyContainerMap.put(propertyName, element.getDeclaringClass()); boolean indexed = false; if (element.isAnnotationPresent(Column.class)) { Column columnAnnotation = element.getAnnotation(Column.class); indexed = columnAnnotation != null && columnAnnotation.indexed(); } org.firebrandocm.dao.annotations.Column colAnnotation = element .getAnnotation(org.firebrandocm.dao.annotations.Column.class); boolean lazy = colAnnotation != null && colAnnotation.lazy(); boolean counter = colAnnotation != null && colAnnotation.counter(); addProperty(colAnnotation, propertyName, element.getType(), indexed, lazy, counter, false); log.debug(String.format("added property %s", propertyName)); }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * /*from www .j a v a 2 s.c om*/ * @param field * @return * @throws NoSuchMethodException */ public Method getSetter(Field field) throws NoSuchMethodException { return field.getDeclaringClass().getMethod("set" + capitalizeIndex(field.getName(), 0), field.getType()); }
From source file:ch.algotrader.cache.EntityHandler.java
private void processFields(long entityId, Object obj, List<EntityCacheSubKey> stack) { Validate.notNull(obj, "obj is null"); for (Field field : FieldUtil.getAllFields(obj.getClass())) { Object value = null;//from w ww .j a va 2 s. c o m try { value = field.get(obj); } catch (Exception e) { LOGGER.error("problem getting field", e); } // nothing to do on simple attributes if (FieldUtil.isSimpleAttribute(field) || value == null) { continue; } // if the object already existed but does not have the same reference replace it CacheResponse response = this.cacheManager.put(value, stack); try { if (response.getState() == CacheState.EXISTING && response.getValue() != value) { field.set(obj, response.getValue()); } EntityCacheKey cacheKey = new EntityCacheKey(field.getDeclaringClass(), entityId); this.cacheManager.getEntityCache().attach(cacheKey, field.getName(), value); } catch (IllegalArgumentException e) { LOGGER.error("problem update field value", e); } catch (IllegalAccessException e) { LOGGER.error("problem update field value", e); } } }