List of usage examples for java.lang.reflect Field isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java
public String getDbName(Field field) { if (field.isAnnotationPresent(Column.class)) { Column c = field.getAnnotation(Column.class); return c.name(); } else {/*from ww w .j ava 2 s. co m*/ return getDbName(field.getName()); } }
From source file:org.broadinstitute.sting.utils.help.GenericDocumentationHandler.java
/** * Recursive helper routine to getFieldDoc() * * @param classDoc/*from w w w.j av a 2 s .c o m*/ * @param name * @param primary * @return */ private FieldDoc getFieldDoc(ClassDoc classDoc, String name, boolean primary) { //System.out.printf("Looking for %s in %s%n", name, classDoc.name()); for (FieldDoc fieldDoc : classDoc.fields(false)) { //System.out.printf("fieldDoc " + fieldDoc + " name " + fieldDoc.name()); if (fieldDoc.name().equals(name)) return fieldDoc; Field field = HelpUtils.getFieldForFieldDoc(fieldDoc); if (field == null) throw new RuntimeException("Could not find the field corresponding to " + fieldDoc + ", presumably because the field is inaccessible"); if (field.isAnnotationPresent(ArgumentCollection.class)) { ClassDoc typeDoc = getRootDoc().classNamed(fieldDoc.type().qualifiedTypeName()); if (typeDoc == null) throw new ReviewedStingException("Tried to get javadocs for ArgumentCollection field " + fieldDoc + " but could't find the class in the RootDoc"); else { FieldDoc result = getFieldDoc(typeDoc, name, false); if (result != null) return result; // else keep searching } } } // if we didn't find it here, wander up to the superclass to find the field if (classDoc.superclass() != null) { return getFieldDoc(classDoc.superclass(), name, false); } if (primary) throw new RuntimeException("No field found for expected field " + name); else return null; }
From source file:adalid.core.EntityAtlas.java
@SuppressWarnings("deprecation") private void finaliseProperty(Field field, Property property) { if (field == null || property == null) { return;/*from w w w . j av a 2 s .com*/ } String key = field.getName(); if (key == null || _properties.containsKey(key)) { return; } if (field.isAnnotationPresent(CastingField.class)) { if (property instanceof AbstractDataArtifact) { AbstractDataArtifact artifact = (AbstractDataArtifact) property; artifact.annotate(field); } return; } if (property.isNotDeclared()) { // property.setDeclared(key, _declaringArtifact, field); XS1.declare(property, _declaringArtifact, field); } if (property instanceof AbstractEntity) { AbstractEntity entity = (AbstractEntity) property; referenceIndex++; entity.setReferenceIndex(referenceIndex); } if (property instanceof Entity) { Entity entity = (Entity) property; if (!entity.isFinalised()) { entity.finalise(); } boolean x = property.depth() > 1 || property.isClassInPath(Operation.class); if (!x) { Entity root = entity.getRoot(); if (root != null) { root.getReferencesMap().put(property.getPathString(), property); } } } if (field.isAnnotationPresent(Extension.class)) { } else { _properties.put(key, property); } }
From source file:com.lhings.java.LhingsDevice.java
/** * This method detects the actions, events and status components of the * device using reflection, builds the descriptor of the device and stores * it in the field jsonDescriptor./* w ww .j a v a 2s. c o m*/ * * @throws InitializationException */ private void autoconfigure() throws InitializationException { Class<?> deviceClass = this.getClass(); Map<String, Object> deviceDescriptor = new HashMap<String, Object>(); // List<com.lhings.java.model.Action> actionList = new // ArrayList<com.lhings.java.model.Action>(); List<com.lhings.java.model.Event> eventList = new ArrayList<com.lhings.java.model.Event>(); // inspect class to identify descriptor fields and status components deviceDescriptor.put("actionList", actionDefinitions.values()); deviceDescriptor.put("stateVariableList", statusDefinitions.values()); deviceDescriptor.put("eventList", eventList); DeviceInfo info = deviceClass.getAnnotation(DeviceInfo.class); if (info != null) { deviceDescriptor.put("modelName", info.modelName()); deviceDescriptor.put("manufacturer", info.manufacturer()); deviceDescriptor.put("deviceType", info.deviceType()); deviceDescriptor.put("serialNumber", info.serialNumber()); } else { deviceDescriptor.put("modelName", ""); deviceDescriptor.put("manufacturer", ""); deviceDescriptor.put("deviceType", DEFAULT_DEVICE_TYPE); deviceDescriptor.put("serialNumber", ""); } Field[] fields = deviceClass.getDeclaredFields(); for (Field field : fields) { // discover status components and add them to descriptor if (field.isAnnotationPresent(StatusComponent.class)) { StatusComponent statusComp = field.getAnnotation(StatusComponent.class); String statusComponentName = statusComp.name(); String statusComponentType; try { statusComponentType = tellLhingsType(field.getType().getName()); } catch (InitializationException ex) { // rethrow with appropriate message throw new InitializationException("Initialization failed for device with uuid " + uuid + ". Type " + field.getType().getName() + " is not allowed for field " + field.getName() + ". Methods annotated with @StatusComponent can only have parameters of the following types: int, float, double, boolean, String and java.util.Date."); } // if no name was provided for field, it defaults to the // name used to declare it in source code boolean validStatusComponentName = statusComponentName.matches("^[a-zA-Z0-9_]*$"); if (!validStatusComponentName) { log.warn("\"" + statusComponentName + "\" is not a valid name for a status component. Only alphanumeric and underscore characters are allowed. Taking field name \"" + field.getName() + "\" as status component name."); } if (statusComponentName.isEmpty() || !validStatusComponentName) { statusComponentName = field.getName(); } statusDefinitions.put(statusComponentName, new com.lhings.java.model.StatusComponent(statusComponentName, statusComponentType)); statusFields.put(statusComponentName, field); } // discover events and add them to descriptor if (field.isAnnotationPresent(Event.class)) { Event event = field.getAnnotation(Event.class); String eventName = event.name(); boolean validEventComponentName = eventName.matches("^[a-zA-Z0-9_]*$"); if (!validEventComponentName) { log.warn("\"" + eventName + "\" is not a valid name for an event. Only alphanumeric and underscore characters are allowed. Taking field name \"" + field.getName() + "\" as event name."); } if (eventName.isEmpty() || !validEventComponentName) // default event name is the name of the field { eventName = field.getName(); } com.lhings.java.model.Event eventToAdd = new com.lhings.java.model.Event(eventName); String[] componentNames = event.component_names(); String[] componentTypes = event.component_types(); if (componentNames.length != componentTypes.length) { log.warn("Payload component list for event \"" + eventName + "\" is not valid: wrong number of component types provided."); } else { for (int j = 0; j < componentNames.length; j++) { eventToAdd.getComponents().add(new Argument(componentNames[j], componentTypes[j])); } } eventList.add(eventToAdd); eventDefinitions.add(eventName); } } // inspect class methods to identify possible actions Method[] methods = deviceClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Action.class)) { com.lhings.java.model.Action modelAction = autoconfigureAction(method); String actionName = method.getAnnotation(Action.class).name(); boolean validNameProvided = actionName.matches("^[a-zA-Z0-9_]*$"); if (!validNameProvided) { log.warn("\"" + actionName + "\" is not a valid name for an action. Only alphanumeric and underscore characters are allowed. Taking method name \"" + method.getName() + "\" as action name."); } if (actionName.isEmpty() || !validNameProvided) { actionName = method.getName(); } actionDefinitions.put(actionName, modelAction); } } jsonDescriptor = new JSONObject(deviceDescriptor).toString(); }
From source file:org.jdal.aop.SerializableReference.java
private Object readResolve() throws ObjectStreamException { if (beanFactory == null) { log.error("Can't not deserialize reference without bean factory"); return null; }//from w ww . j a va 2s . com if (useMemoryCache) { Object ret = serializedObjects.remove(this.id); if (ret != null) { if (log.isDebugEnabled()) log.debug("Removed a serialized reference. serialized objects size [" + serializedObjects.size() + "]"); return getSerializableProxy(ret); } } if (targetBeanName != null) { if (log.isDebugEnabled()) log.debug("Resolving serializable object to bean name [" + targetBeanName + "]"); return getSerializableProxy(); } if (log.isDebugEnabled()) log.debug("Resolving serializable object for [" + descriptor.getDependencyName() + "]"); Field field = descriptor.getField(); // Check bean definition BeanDefinition rbd = beanFactory.getBeanDefinition(beanName); PropertyValues pvs = rbd.getPropertyValues(); if (pvs.contains(field.getName())) { Object value = pvs.getPropertyValue(field.getName()); if (value instanceof BeanReference) { // cache the bean name this.targetBeanName = ((BeanReference) value).getBeanName(); return getSerializableProxy(); } } // Check Autowired try { Object bean = beanFactory.resolveDependency(descriptor, beanName); if (bean != null) return getSerializableProxy(bean); } catch (BeansException be) { // dependency not found. } // Check Resource annotation if (field.isAnnotationPresent(Resource.class)) { Resource r = field.getAnnotation(Resource.class); String name = StringUtils.isEmpty(r.name()) ? descriptor.getField().getName() : r.name(); if (beanFactory.containsBean(name)) { this.targetBeanName = name; return getSerializableProxy(); } } // Try with depend beans. String[] dependentBeans = beanFactory.getDependenciesForBean(beanName); List<String> candidates = new ArrayList<String>(); for (String name : dependentBeans) { if (beanFactory.isTypeMatch(name, descriptor.getDependencyType())) ; candidates.add(name); } if (candidates.size() == 1) return getSerializableProxy(beanFactory.getBean(candidates.get(0))); if (candidates.size() > 1) { for (PropertyValue pv : pvs.getPropertyValues()) { if (pv.getValue() instanceof BeanReference) { BeanReference br = (BeanReference) pv.getValue(); if (candidates.contains(br.getBeanName())) return getSerializableProxy(beanFactory.getBean(br.getBeanName())); } } } log.error("Cant not resolve serializable reference wiht candidates " + candidates.toArray()); return null; }
From source file:org.mayocat.search.elasticsearch.AbstractGenericEntityIndexDocumentPurveyor.java
protected Map<String, Object> extractSourceFromEntity(Entity entity, Tenant tenant) { Map<String, Object> source = Maps.newHashMap(); Map<String, Object> properties = Maps.newHashMap(); boolean hasClassLevelIndexAnnotation = entity.getClass().isAnnotationPresent(Index.class); for (Field field : entity.getClass().getDeclaredFields()) { boolean isAccessible = field.isAccessible(); try {// w ww .j a v a2 s . co m if (Modifier.isStatic(field.getModifiers())) { // we're not interested in static fields like serialVersionUid (or any other static field) continue; } if (Identifiable.class.isAssignableFrom(entity.getClass()) && field.getName().equals("id")) { // do not index the id of identifiable under properties continue; } if (Slug.class.isAssignableFrom(entity.getClass()) && field.getName().equals("slug")) { // do not index the slug of slugs under properties // (it is indexed as a top level property) continue; } field.setAccessible(true); boolean searchIgnoreFlag = field.isAnnotationPresent(DoNotIndex.class); boolean indexFlag = field.isAnnotationPresent(Index.class); if ((hasClassLevelIndexAnnotation || indexFlag) && !searchIgnoreFlag) { if (field.get(entity) != null) { Class fieldClass = field.get(entity).getClass(); if (isAddonField(fieldClass, field)) { // Treat addons differently. // They're not located in the "properties" object like the other entity properties, // but they're stored in their own "addon" object Association<Map<String, AddonGroup>> addons = (Association<Map<String, AddonGroup>>) field .get(entity); if (addons.isLoaded()) { source.put("addons", extractAddons(addons.get())); } } else if (BigDecimal.class.isAssignableFrom(fieldClass)) { // Convert big decimal to double value properties.put(field.getName(), ((BigDecimal) field.get(entity)).doubleValue()); } else { // General case o> properties.put(field.getName(), field.get(entity)); } } else { properties.put(field.getName(), null); } } } catch (IllegalAccessException e) { this.logger.error("Error extracting entity", entity.getSlug(), e); } catch (JsonMappingException e) { this.logger.error("Error extracting entity", entity.getSlug(), e); } catch (JsonParseException e) { this.logger.error("Error extracting entity", entity.getSlug(), e); } catch (JsonProcessingException e) { this.logger.error("Error extracting entity", entity.getSlug(), e); } catch (IOException e) { this.logger.error("Error extracting entity", entity.getSlug(), e); } finally { field.setAccessible(isAccessible); } } source.put("properties", properties); if (HasFeaturedImage.class.isAssignableFrom(entity.getClass())) { HasFeaturedImage hasFeaturedImage = (HasFeaturedImage) entity; if (hasFeaturedImage.getFeaturedImageId() != null) { Attachment attachment = attachmentStore.findAndLoadById(hasFeaturedImage.getFeaturedImageId()); if (attachment != null) { Map<String, Object> imageMap = Maps.newHashMap(); imageMap.put("url", entityURLFactory.create(attachment, tenant)); imageMap.put("title", attachment.getTitle()); imageMap.put("extension", attachment.getExtension()); source.put("featuredImage", imageMap); } } } source.put("url", entityURLFactory.create(entity, tenant).toString()); source.put("api_url", entityURLFactory.create(entity, tenant, URLType.API).toString()); source.put("slug", entity.getSlug()); return source; }
From source file:com.haulmont.cuba.core.global.MetadataTools.java
/** * Determine whether the given annotation is present in the object's class or in any of its superclasses. * * @param javaClass entity class//w ww. ja v a 2s .c om * @param property property name * @param annotationClass annotation class * @return */ public boolean isAnnotationPresent(Class javaClass, String property, Class<? extends Annotation> annotationClass) { Field field; try { field = javaClass.getDeclaredField(property); return field.isAnnotationPresent(annotationClass); } catch (NoSuchFieldException e) { Class superclass = javaClass.getSuperclass(); while (superclass != null) { try { field = superclass.getDeclaredField(property); return field.isAnnotationPresent(annotationClass); } catch (NoSuchFieldException e1) { superclass = superclass.getSuperclass(); } } throw new RuntimeException("Property not found: " + property); } }
From source file:jp.co.opentone.bsol.linkbinder.view.AbstractPage.java
private Map<String, Object> collectTransferValues() { Map<String, Object> values = new HashMap<String, Object>(); for (Field field : getClass().getDeclaredFields()) { if (field.isAnnotationPresent(Transfer.class)) { field.setAccessible(true);//w w w .j a v a2s. c o m try { Object value = field.get(this); if (value != null) { values.put(field.getName(), field.get(this)); } } catch (IllegalArgumentException e) { throw new ReflectionRuntimeException(e); } catch (IllegalAccessException e) { throw new ReflectionRuntimeException(e); } } } return values; }
From source file:org.broadinstitute.gatk.utils.help.GenericDocumentationHandler.java
/** * Recursive helper routine to getFieldDoc() * * @param classDoc//from ww w. j av a 2 s . c o m * @param name * @param primary * @return */ private FieldDoc getFieldDoc(ClassDoc classDoc, String name, boolean primary) { //System.out.printf("Looking for %s in %s%n", name, classDoc.name()); for (FieldDoc fieldDoc : classDoc.fields(false)) { //System.out.printf("fieldDoc " + fieldDoc + " name " + fieldDoc.name()); if (fieldDoc.name().equals(name)) return fieldDoc; Field field = DocletUtils.getFieldForFieldDoc(fieldDoc); if (field == null) throw new RuntimeException("Could not find the field corresponding to " + fieldDoc + ", presumably because the field is inaccessible"); if (field.isAnnotationPresent(ArgumentCollection.class)) { ClassDoc typeDoc = getRootDoc().classNamed(fieldDoc.type().qualifiedTypeName()); if (typeDoc == null) throw new ReviewedGATKException("Tried to get javadocs for ArgumentCollection field " + fieldDoc + " but could't find the class in the RootDoc"); else { FieldDoc result = getFieldDoc(typeDoc, name, false); if (result != null) return result; // else keep searching } } } // if we didn't find it here, wander up to the superclass to find the field if (classDoc.superclass() != null) { return getFieldDoc(classDoc.superclass(), name, false); } if (primary) throw new RuntimeException("No field found for expected field " + name); else return null; }
From source file:org.broadinstitute.gatk.utils.commandline.ParsingEngine.java
/** * Extract all the argument sources from a given object, along with their bindings if obj != null . * @param obj the object corresponding to the sourceClass * @param sourceClass class to act as sources for other arguments. * @param parentFields Parent Fields/*www. j ava2 s. c o m*/ * @return A map of sources associated with this object and its aggregated objects and bindings to their bindings values */ private Map<ArgumentSource, Object> extractArgumentBindings(Object obj, Class sourceClass, Field[] parentFields) { Map<ArgumentSource, Object> bindings = new LinkedHashMap<ArgumentSource, Object>(); while (sourceClass != null) { Field[] fields = sourceClass.getDeclaredFields(); for (Field field : fields) { if (ArgumentTypeDescriptor.isArgumentAnnotationPresent(field)) { Object val = obj != null ? JVMUtils.getFieldValue(field, obj) : null; bindings.put(new ArgumentSource(parentFields, field, selectBestTypeDescriptor(field.getType())), val); } if (field.isAnnotationPresent(ArgumentCollection.class)) { Object val = obj != null ? JVMUtils.getFieldValue(field, obj) : null; Field[] newParentFields = Arrays.copyOf(parentFields, parentFields.length + 1); newParentFields[parentFields.length] = field; bindings.putAll(extractArgumentBindings(val, field.getType(), newParentFields)); } } sourceClass = sourceClass.getSuperclass(); } return bindings; }