List of usage examples for java.lang.reflect Field getDeclaringClass
@Override
public Class<?> getDeclaringClass()
From source file:org.firebrandocm.dao.ClassMeta.java
/** * Processes metadata for a simple column. Helper method */*from w w w . j av a2 s . c o m*/ * @param element the type * @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.projectforge.core.ConfigXml.java
public String exportConfiguration() { final XmlObjectWriter writer = new XmlObjectWriter() { @Override//from w w w . java 2 s . c o m protected boolean ignoreField(final Object obj, final Field field) { if (field.getDeclaringClass().isAssignableFrom(ConfigXml.class) == true && StringHelper.isIn(field.getName(), "expireTime", "timeOfLastRefresh") == true) { return true; } return super.ignoreField(obj, field); } }; final String xml = writer.writeToXml(this, true); return XmlHelper.XML_HEADER + xml; }
From source file:org.unitils.inject.InjectModule.java
/** * Creates an objects of the given fields' declared type and assigns it to this field on the given testObject * * @param testObject The test instance, not null * @param testedObjectField The tested object field, not null *//*from ww w .jav a 2s .co m*/ protected void createObjectForField(Object testObject, Field testedObjectField) { Class<?> declaredClass = testedObjectField.getType(); if (declaredClass.isInterface()) { logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type " + testedObjectField.getType().getSimpleName() + " which is an interface type. It is not automatically instantiated."); } else if (isAbstract(declaredClass.getModifiers())) { logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type " + testedObjectField.getDeclaringClass().getSimpleName() + " which is an abstract class. It is not automatically instantiated."); } else { try { declaredClass.getDeclaredConstructor(); Object instance = createInstanceOfType(declaredClass, true); setFieldValue(testObject, testedObjectField, instance); } catch (NoSuchMethodException e) { logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type " + testedObjectField.getDeclaringClass().getSimpleName() + " which has no default (parameterless) constructor. It is not automatically instantiated."); } } }
From source file:org.tdar.core.service.ReflectionService.java
/** * Call the setter of the supplied object and field with the supplied value * //from w w w. ja v a 2 s . c o m * @param obj * @param field * @param fieldValue */ public <T> void callFieldSetter(Object obj, Field field, T fieldValue) { String setterName = generateSetterName(field); String valClass = "null"; if (fieldValue != null) { valClass = fieldValue.getClass().getSimpleName(); } logger.trace("Calling {}.{}({})", new Object[] { field.getDeclaringClass().getSimpleName(), setterName, valClass }); // here we assume that field's type is assignable from the fieldValue Method setter = ReflectionUtils.findMethod(field.getDeclaringClass(), setterName, field.getType()); try { setter.invoke(obj, fieldValue); } catch (Exception e) { logger.debug("cannot call field setter {} on : {} {} {}", field, obj, fieldValue, e); } }
From source file:beans.config.ConfigBean.java
private void injectConfiguration(Object obj, Configuration conf) { Set<Field> allFields = ReflectionUtils.getAllFields(obj.getClass(), Predicates.alwaysTrue()); for (Field field : allFields) { String configKey = field.getName(); Config configAnn = null;// w w w . ja v a 2s. co m if (field.isAnnotationPresent(Config.class)) { configAnn = field.getAnnotation(Config.class); String playKey = configAnn.playKey(); // use the annotated information only if not empty. configKey = StringUtils.isEmpty(playKey) ? configKey : playKey; } if (handlers.containsKey(field.getType())) { try { Object value = handlers.get(field.getType()).getValue(conf, configKey); if (value != null || !isIgnoreNullValue(configAnn)) { field.set(obj, value); } } catch (Exception e) { logger.error(String.format("unable to set value for field [%s.%s]", field.getDeclaringClass().getName(), field.getName()), e); } } else { // this is probably an Object. need to instantiate try { if (conf.getConfig(configKey) != null) { // important : we assume the field is not null. // this way we will be able to refresh configuration on command. Object value = field.get(obj); injectConfiguration(value, conf.getConfig(configKey)); } } catch (Exception e) { throw new RuntimeException(String.format("unable to populate configuration for key %s.%s", obj.getClass(), field.getName()), e); } } ConfigValueHandler handler = handlers.containsKey(field.getType()) ? handlers.get(field.getType()) : handlers.get(Configuration.class); } }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * //from w ww . ja va 2 s .c om * @param field * @return * @throws NoSuchMethodException */ public Method getGetter(Field field) throws NoSuchMethodException { if (isBoolean(field.getType())) return field.getDeclaringClass().getMethod("is" + capitalizeIndex(field.getName(), 0)); else return field.getDeclaringClass().getMethod("get" + capitalizeIndex(field.getName(), 0)); }
From source file:org.mybatisorm.annotation.handler.JoinHandler.java
private Hashtable<Set<Class<?>>, LinkedList<Field[]>> getRefMap(List<Field> fields) { Map<String, Class<?>> classMap = new HashMap<String, Class<?>>(); List<Field> refFields = new ArrayList<Field>(); TableHandler handler = null;/*w w w. ja v a 2 s . c om*/ for (Field field : fields) { Class<?> clazz = field.getType(); if (!TableHandler.hasAnnotation(clazz)) throw new AnnotationNotFoundException( "The property class " + clazz.getName() + " has no @Table annotation."); classMap.put(clazz.getSimpleName(), clazz); handler = HandlerFactory.getHandler(clazz); refFields.addAll(handler.getReferenceFields()); } Hashtable<Set<Class<?>>, LinkedList<Field[]>> refMap = new Hashtable<Set<Class<?>>, LinkedList<Field[]>>(); for (Field field : refFields) { Class<?> clazz = field.getDeclaringClass(); String[] ref = field.getAnnotation(Column.class).references().split("\\."); if (ref.length < 2) throw new InvalidAnnotationException(clazz.getSimpleName() + "." + field.getName() + " has invalid references property in @Column annotation."); Class<?> refClazz = classMap.get(ref[0]); if (refClazz == null) continue; Set<Class<?>> pair = pair(clazz, refClazz); LinkedList<Field[]> list = refMap.get(pair); if (list == null) { list = new LinkedList<Field[]>(); refMap.put(pair, list); } Field refField = null; try { refField = refClazz.getDeclaredField(ref[1]); } catch (Exception e) { throw new InvalidAnnotationException("The " + ref[0] + " class has no " + ref[1] + " property."); } list.add(new Field[] { refField, field }); } return refMap; }
From source file:com.ocpsoft.pretty.faces.config.annotation.PrettyAnnotationHandler.java
/** * Searches for {@link URLQueryParameter} annotations on a single field. * //from www. ja va2 s . c om * @param field Field to scan * @param classMappingIds The mapping IDs of the class this method belongs to */ private void processFieldAnnotations(Field field, String[] classMappingIds) { // Is there a @URLQueryParameter annotation? URLQueryParameter queryParamAnnotation = field.getAnnotation(URLQueryParameter.class); if (queryParamAnnotation != null) { // create a QueryParamSpec from the annotation QueryParamSpec queryParam = new QueryParamSpec(); queryParam.setFieldName(field.getName()); queryParam.setOwnerClass(field.getDeclaringClass()); queryParam.setName(queryParamAnnotation.value()); queryParam.setOnPostback(queryParamAnnotation.onPostback()); // check which mapping the action belongs to if (!isBlank(queryParamAnnotation.mappingId())) { // action belongs to the mapping mentioned with mappingId attribute queryParam.setMappingIds(new String[] { queryParamAnnotation.mappingId().trim() }); } else if (classMappingIds != null && classMappingIds.length > 0) { // use the mappings found on the class queryParam.setMappingIds(classMappingIds); } else { throw new IllegalArgumentException("Unable to find a suitable mapping " + "for the query-parameter definied on field '" + field.getName() + "' in class '" + field.getDeclaringClass().getName() + "'. Either place a @URLMapping annotation on the " + "class or reference a foreign mapping using the 'mappingId' attribute."); } // check if there is also a validation annotation placed on the field URLValidator validationAnnotation = field.getAnnotation(URLValidator.class); // check if annotation has been found if (validationAnnotation != null) { // set validation options on the QueryParamSpec object queryParam.setValidatorIds(validationAnnotation.validatorIds()); queryParam.setOnError(validationAnnotation.onError()); queryParam.setValidator(validationAnnotation.validator()); } // add the new spec object to the list of specs queryParamList.add(queryParam); } }
From source file:org.apache.camel.dataformat.bindy.BindyKeyValuePairFactory.java
/** * //from w ww . jav a 2s. c om */ public String unbind(Map<String, Object> model) throws Exception { StringBuilder builder = new StringBuilder(); Map<Integer, KeyValuePairField> keyValuePairFieldsSorted = new TreeMap<Integer, KeyValuePairField>( keyValuePairFields); Iterator<Integer> it = keyValuePairFieldsSorted.keySet().iterator(); // Map containing the OUT position of the field // The key is double and is created using the position of the field and // location of the class in the message (using section) Map<Integer, String> positions = new TreeMap<Integer, String>(); // Check if separator exists ObjectHelper.notNull(this.pairSeparator, "The pair separator has not been instantiated or property not defined in the @Message annotation"); char separator = Converter.getCharDelimitor(this.getPairSeparator()); if (LOG.isDebugEnabled()) { LOG.debug("Separator converted : '0x" + Integer.toHexString(separator) + "', from : " + this.getPairSeparator()); } while (it.hasNext()) { KeyValuePairField keyValuePairField = keyValuePairFieldsSorted.get(it.next()); ObjectHelper.notNull(keyValuePairField, "KeyValuePair is null !"); // Retrieve the field Field field = annotedFields.get(keyValuePairField.tag()); // Change accessibility to allow to read protected/private fields field.setAccessible(true); if (LOG.isDebugEnabled()) { LOG.debug("Tag : " + keyValuePairField.tag() + ", Field type : " + field.getType() + ", class : " + field.getDeclaringClass().getName()); } // Retrieve the format, pattern and precision associated to the type Class<?> type = field.getType(); String pattern = keyValuePairField.pattern(); int precision = keyValuePairField.precision(); // Create format Format format = FormatFactory.getFormat(type, pattern, getLocale(), precision); // Get object to be formatted Object obj = model.get(field.getDeclaringClass().getName()); if (obj != null) { // Get field value Object keyValue = field.get(obj); if (this.isMessageOrdered()) { // Generate a key using the number of the section // and the position of the field Integer key1 = sections.get(obj.getClass().getName()); Integer key2 = keyValuePairField.position(); if (LOG.isDebugEnabled()) { LOG.debug("Key of the section : " + key1 + ", and the field : " + key2); } Integer keyGenerated = generateKey(key1, key2); if (LOG.isDebugEnabled()) { LOG.debug("Key generated : " + String.valueOf(keyGenerated) + ", for section : " + key1); } // Add value to the list if not null if (keyValue != null) { // Format field value String valueFormated; try { valueFormated = format.format(keyValue); } catch (Exception e) { throw new IllegalArgumentException( "Formating error detected for the tag : " + keyValuePairField.tag(), e); } // Create the key value string String value = keyValuePairField.tag() + this.getKeyValuePairSeparator() + valueFormated; if (LOG.isDebugEnabled()) { LOG.debug("Value to be formatted : " + keyValue + ", for the tag : " + keyValuePairField.tag() + ", and its formated value : " + valueFormated); } // Add the content to the TreeMap according to the // position defined positions.put(keyGenerated, value); if (LOG.isDebugEnabled()) { LOG.debug("Positions size : " + positions.size()); } } } else { // Add value to the list if not null if (keyValue != null) { // Format field value String valueFormated; try { valueFormated = format.format(keyValue); } catch (Exception e) { throw new IllegalArgumentException( "Formating error detected for the tag : " + keyValuePairField.tag(), e); } // Create the key value string String value = keyValuePairField.tag() + this.getKeyValuePairSeparator() + valueFormated + separator; // Add content to the stringBuilder builder.append(value); if (LOG.isDebugEnabled()) { LOG.debug("Value added : " + keyValuePairField.tag() + this.getKeyValuePairSeparator() + valueFormated + separator); } } } } } // Iterate through the list to generate // the message according to the order/position if (this.isMessageOrdered()) { Iterator<Integer> posit = positions.keySet().iterator(); while (posit.hasNext()) { String value = positions.get(posit.next()); if (LOG.isDebugEnabled()) { LOG.debug("Value added at the position (" + posit + ") : " + value + separator); } builder.append(value + separator); } } return builder.toString(); }
From source file:adalid.core.EntityAtlas.java
@SuppressWarnings("deprecation") void initialiseFields(Class<?> clazz) { track("initialiseFields", _declaringArtifact, clazz.getSimpleName()); Class<?> c;//from w w w .j a v a 2 s .c o m int d, r; String name; String key; String pattern = "there are several fields for operation {0}"; String message; Class<?> type; Class<?> decl; Class<?> operationClass; Field operationField; int modifiers; boolean restricted; Object o; int depth = _declaringArtifact.depth(); int round = _declaringArtifact.round(); Class<?>[] classes = new Class<?>[] { Property.class, Key.class, Tab.class, View.class, Instance.class, NamedValue.class, Expression.class, Transition.class, Operation.class, Trigger.class }; Class<?> dac = _declaringArtifact.getClass(); Class<?> top = Entity.class; int i = ArrayUtils.indexOf(classes, clazz); if (i != ArrayUtils.INDEX_NOT_FOUND) { c = classes[i]; for (Field field : XS1.getFields(dac, top)) { field.setAccessible(true); logger.trace(field); name = field.getName(); type = field.getType(); decl = field.getDeclaringClass(); if (!c.isAssignableFrom(type)) { continue; } if (c.equals(Expression.class) && Property.class.isAssignableFrom(type)) { continue; } // TODO: extension handling if (field.isAnnotationPresent(Extension.class) && Entity.class.isAssignableFrom(type)) { // if (!dac.equals(decl) || !dac.isAssignableFrom(type)) { // continue; // } continue; } modifiers = type.getModifiers(); if (NamedValue.class.isAssignableFrom(type) || Expression.class.isAssignableFrom(type)) { restricted = false; } else { restricted = type.isInterface() || Modifier.isAbstract(modifiers); } restricted = restricted || !Modifier.isPublic(modifiers); if (restricted) { continue; } modifiers = field.getModifiers(); restricted = Modifier.isPrivate(modifiers); if (restricted) { continue; } restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers); if (restricted) { continue; } if (Operation.class.isAssignableFrom(type)) { key = type.getSimpleName(); operationClass = _operationClasses.get(key); if (operationClass != null) { operationField = _operationFields.get(key); if (operationField == null) { _operationFields.put(key, field); } else { message = MessageFormat.format(pattern, operationClass.getName()); logger.warn(message); TLC.getProject().getParser().increaseWarningCount(); } } } String errmsg = "failed to create a new instance of field \"" + field + "\" at " + _declaringArtifact; try { o = field.get(_declaringArtifact); if (o == null) { logger.debug(message(type, name, o, depth, round)); o = XS1.initialiseField(_declaringArtifact, field); if (o == null) { logger.debug(message(type, name, o, depth, round)); // throw new RuntimeException(message(type, name, o, depth, round)); } else { logger.debug(message(type, name, o, depth, round)); field.set(_declaringArtifact, o); } } } catch (IllegalArgumentException | IllegalAccessException ex) { throw new InstantiationRuntimeException(errmsg, ex); } } } }