Java 类org.reflections.scanners.FieldAnnotationsScanner 实例源码

项目:soundwave    文件:EsMapper.java   
/**
 * Get fields for a type. It extracts all JsonProperty fields
 * @param type
 * @return
 */
public static String[] getIncludeFields(Class type) {
  if (!fieldsCache.containsKey(type.getTypeName())) {
    Reflections
        reflections =
        new Reflections(type.getCanonicalName(), new FieldAnnotationsScanner());
    List<String> ret = new ArrayList<>();
    for (Field field : reflections.getFieldsAnnotatedWith(JsonProperty.class)) {
      JsonProperty property = field.getAnnotation(JsonProperty.class);
      ret.add(property.value());
    }

    if (type.getSuperclass() != null) {
      ret.addAll(Arrays.asList(getIncludeFields(type.getSuperclass())));
    }

    fieldsCache.putIfAbsent(type.getTypeName(), ret.toArray(new String[ret.size()]));
  }
  return fieldsCache.get(type.getTypeName());
}
项目:typesafeconfig-guice    文件:TypesafeConfigModule.java   
/**
 * Scans the specified packages for annotated classes, and applies Config values to them.
 * 
 * @param config the Config to derive values from
 * @param packageNamePrefix the prefix to limit scanning to - e.g. "com.github"
 * @return The constructed TypesafeConfigModule.
 */
public static TypesafeConfigModule fromConfigWithPackage(Config config, String packageNamePrefix) {
     ConfigurationBuilder configBuilder = 
         new ConfigurationBuilder()
         .filterInputsBy(new FilterBuilder().includePackage(packageNamePrefix))
         .setUrls(ClasspathHelper.forPackage(packageNamePrefix))
         .setScanners(
            new TypeAnnotationsScanner(), 
            new MethodParameterScanner(), 
            new MethodAnnotationsScanner(), 
            new FieldAnnotationsScanner()
         );
    Reflections reflections = new Reflections(configBuilder);

    return new TypesafeConfigModule(config, reflections);
}
项目:restapidoc    文件:ClassPathScanner.java   
private void init(String packageName) {
  FilterBuilder filters = new FilterBuilder().includePackage(packageName);

  Scanner[] scanners = {
      new TypeAnnotationsScanner(),
      new MethodAnnotationsScanner(),
      new MethodParameterScanner(),
      new FieldAnnotationsScanner(),
      new SubTypesScanner().filterResultsBy(filters)
  };

  reflections = new ConfigurationBuilder()
      .addUrls(ClasspathHelper.forPackage(packageName))
      .addScanners(scanners)
      .filterInputsBy(filters)
      .build();
}
项目:bottimus    文件:ConfigurationBuilder.java   
/**
 * Loads the configuration
 * @throws IOException
 */
public void build() throws IOException {
    if (configFile == null) throw new IllegalStateException("File not initialized");

    Reflections reflections = new Reflections(new org.reflections.util.ConfigurationBuilder()
            .setUrls(ClasspathHelper.forClass(Configuration.class))
            .addScanners(new FieldAnnotationsScanner()));
    Set<Field> options = reflections.getFieldsAnnotatedWith(Option.class);

    // Load config file if it exists
    if (configFile.exists()) properties.load(new FileInputStream(configFile));

    // Load configuration fields
    options.forEach(o -> {
        Option option = o.getAnnotation(Option.class);
        try {
            Object value = configFile.exists()
                    ? properties.getOrDefault(option.value(), o.get(null))
                    : o.get(null);
            o.setAccessible(true);
            o.set(null, value);
            if (value.getClass().isAssignableFrom(String.class)) {
                properties.setProperty(option.value(), (String) value);
            }
        } catch (IllegalAccessException e) {
            LOG.severe("Could not load configuration, IllegalAccessException");
            System.exit(-1);
        }
    });

    // Write the full configuration file
    properties.store(new FileOutputStream(configFile), null);
}
项目:java-flagz    文件:ReflectionsCache.java   
static synchronized Reflections reflectionsForPrefixes(List<String> prefixes) {
  if (packagePrefixesToReflections.containsKey(prefixes)) {
    return packagePrefixesToReflections.get(prefixes);
  }
  ConfigurationBuilder builder = new ConfigurationBuilder()
      .setUrls(urlsToReflect(prefixes))
      .setScanners(
          new FieldAnnotationsScanner(),
          new SubTypesScanner());
  Reflections reflections = new Reflections(builder);
  packagePrefixesToReflections.put(prefixes, reflections);
  return reflections;
}
项目:anno4j    文件:Anno4j.java   
public Anno4j(Repository repository, IDGenerator idGenerator, URI defaultContext, boolean persistSchemaAnnotations, Set<URL> additionalClasses) throws RepositoryConfigException, RepositoryException {
    this.idGenerator = idGenerator;
    this.defaultContext = defaultContext;

    classpath = new HashSet<>();
    classpath.addAll(ClasspathHelper.forClassLoader());
    classpath.addAll(ClasspathHelper.forJavaClassPath());
    classpath.addAll(ClasspathHelper.forManifest());
    classpath.addAll(ClasspathHelper.forPackage(""));
    if(additionalClasses != null) {
        classpath.addAll(additionalClasses);
    }

    Reflections annotatedClasses = new Reflections(new ConfigurationBuilder()
            .setUrls(classpath)
            .useParallelExecutor()
            .filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun"))
            .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new FieldAnnotationsScanner()));

    // Bugfix: Searching for Reflections creates a lot ot Threads, that are not closed at the end by themselves,
    // so we close them manually.
    annotatedClasses.getConfiguration().getExecutorService().shutdown();

    // find classes with @Partial annotation
    this.partialClasses = annotatedClasses.getTypesAnnotatedWith(Partial.class, true);

    scanForEvaluators(annotatedClasses);

    if(!repository.isInitialized()) {
        repository.initialize();
    }

    this.setRepository(repository, additionalClasses, additionalClasses);

    // Persist schema information to repository:
    if(persistSchemaAnnotations) {
        persistSchemaAnnotations(annotatedClasses);
    }
}
项目:anno4j    文件:OWLSchemaPersistingManagerTest.java   
@Test
public void testMatchingExistingSchema() throws Exception {
    Anno4j anno4j = new Anno4j();

    OWLClazz myPerson = anno4j.createObject(OWLClazz.class, (Resource) new URIImpl("http://example.de/#validly_annotated_person"));
    RDFSProperty bossProperty = anno4j.createObject(RDFSProperty.class, (Resource) new URIImpl("http://example.de/#has_boss"));

    Restriction bossAllValuesFromRestr = anno4j.createObject(Restriction.class);
    bossAllValuesFromRestr.setOnClazz(Sets.newHashSet(myPerson));
    bossAllValuesFromRestr.setOnProperty(Sets.newHashSet(bossProperty));
    bossAllValuesFromRestr.setAllValuesFrom(Sets.<OWLClazz>newHashSet(myPerson));

    Reflections types = new Reflections(
            new ConfigurationBuilder()
                    .setUrls(
                            ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()),
                            ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader())
                    )
                    .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner())
    );

    Transaction transaction = anno4j.createTransaction();
    transaction.begin();
    SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection());

    boolean exceptionThrown = false;
    try {
        persistingManager.persistSchema(types);
    } catch (SchemaPersistingManager.ContradictorySchemaException e) {
        exceptionThrown = true;
    }
    assertFalse(exceptionThrown);
}
项目:anno4j    文件:OWLSchemaPersistingManagerTest.java   
@Test
public void testContradictoryExistingSchema() throws Exception {
    Anno4j anno4j = new Anno4j();

    Transaction setupTransaction = anno4j.createTransaction();
    setupTransaction.begin();
    setupTransaction.getConnection().prepareUpdate("INSERT DATA {" +
            "  <http://example.de/#validly_annotated_person> rdfs:subClassOf _:restr . " +
            "  _:restr a owl:Restriction . " +
            "  _:restr owl:onProperty <http://example.de/#id> . " +
            "  _:restr owl:minCardinality '42'^^xsd:nonNegativeInteger . " +
            "}").execute();
    setupTransaction.commit();

    Transaction transaction = anno4j.createTransaction();
    transaction.begin();
    SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection());

    Reflections types = new Reflections(
            new ConfigurationBuilder()
                    .setUrls(
                            ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()),
                            ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader())
                    )
                    .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner())
    );

    boolean exceptionThrown = false;
    try {
        persistingManager.persistSchema(types);
    } catch (SchemaPersistingManager.ContradictorySchemaException e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown);
}
项目:tempto    文件:ReflectionHelper.java   
@Override
public Set<Field> load(Class<? extends Annotation> key)
        throws Exception
{
    Reflections reflections = new Reflections(forPackage(PACKAGES_PREFIX),
            new FieldAnnotationsScanner(), ReflectionHelper.class.getClassLoader());
    return unmodifiableSet(reflections.getFieldsAnnotatedWith(key));
}
项目:reflections    文件:ReflectionUtilsTest.java   
@Test
public void getAllAndReflections() {
    Reflections reflections = new Reflections(TestModel.class, new FieldAnnotationsScanner());

    Set<Field> af1 = reflections.getFieldsAnnotatedWith(TestModel.AF1.class);
    Set<? extends Field> allFields = ReflectionUtils.getAll(af1, withModifier(Modifier.PROTECTED));
    assertTrue(allFields.size() == 1);
    assertThat(allFields, names("f2"));
}
项目:groningen    文件:SettingsProvider.java   
private Collection<Field> findAnnotatedFields() {
  final Reflections reflections = new Reflections(new ConfigurationBuilder()
      .filterInputsBy(new FilterBuilder()
          .include(FilterBuilder.prefix(PROXIED_FLAGS_PACKAGE_WHITELIST_PREFIX)))
      .setUrls(ClasspathHelper.forPackage(PROXIED_FLAGS_PACKAGE_WHITELIST_PREFIX))
      .setScanners(new FieldAnnotationsScanner()));

  return reflections.getFieldsAnnotatedWith(Option.class);
}
项目:backstopper    文件:ReflectionBasedJsr303AnnotationTrollerBase.java   
/**
 * Initializes the instance based on what is returned by {@link #ignoreAllAnnotationsAssociatedWithTheseProjectClasses()}
 * and {@link #specificAnnotationDeclarationExclusionsForProject()}. This is time consuming and should only be done
 * once per project if possible - see the usage info in the {@link ReflectionBasedJsr303AnnotationTrollerBase}
 * class-level javadocs.
 *
 * <p>The given set of extra packages for constraint annotation searching will be passed into {@link
 * #getFinalPackagesToSearchForConstraintAnnotations(Set)} to generate the final set of packages that are searched.
 * If you don't want the {@link #DEFAULT_CONSTRAINT_SEARCH_PACKAGES} default packages to be searched you can
 * override {@link #getDefaultPackagesToSearchForConstraintAnnotations()}.
 */
public ReflectionBasedJsr303AnnotationTrollerBase(Set<String> extraPackagesForConstraintAnnotationSearch) {

    /*
     * Set up the {@link #ignoreAllAnnotationsAssociatedWithTheseClasses} and
     * {@link #specificAnnotationDeclarationsExcludedFromStrictMessageRequirement} fields so we know which
     * annotations are project-relevant vs. unit-test-only.
     */
    ignoreAllAnnotationsAssociatedWithTheseClasses =
        new ArrayList<>(setupIgnoreAllAnnotationsAssociatedWithTheseClasses());
    specificAnnotationDeclarationsExcludedFromStrictMessageRequirement =
        new ArrayList<>(setupSpecificAnnotationDeclarationExclusions());

    /*
     * Set up the {@link #reflections}, {@link #constraintAnnotationClasses}, and
     * {@link #allConstraintAnnotationsMasterList} fields. This is where the crazy reflection magic happens to troll
     * the project for the JSR 303 annotation declarations.
     */
    // Create the ConfigurationBuilder to search the relevant set of packages.
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    for (String packageToAdd : getFinalPackagesToSearchForConstraintAnnotations(
        extraPackagesForConstraintAnnotationSearch)) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(packageToAdd));
    }

    // Create the Reflections object so it scans for all validation annotations we care about and all project
    //      classes that might have annotations on them.
    reflections = new Reflections(configurationBuilder.setScanners(
        new SubTypesScanner(), new MethodParameterScanner(), new TypeAnnotationsScanner(),
        new MethodAnnotationsScanner(), new FieldAnnotationsScanner()
    ));

    // Gather the list of all JSR 303 validation annotations in the project. Per the JSR 303 spec this is any
    //      annotation class type that is marked with @Constraint.
    constraintAnnotationClasses = new ArrayList<>();
    for (Class<?> constraintAnnotatedType : reflections.getTypesAnnotatedWith(Constraint.class, true)) {
        if (constraintAnnotatedType.isAnnotation()) {
            //noinspection unchecked
            constraintAnnotationClasses.add((Class<? extends Annotation>) constraintAnnotatedType);
        }
    }

    // We're not done gathering validation annotations though, unfortunately. JSR 303 also says that *any*
    //      annotation (whether it is a Constraint or not) that has a value field that returns an array of actual
    //      Constraints is treated as a "multi-value constraint", and the validation processor will run each
    //      of the Constraints in the array as if they were declared separately on the annotated element. Therefore,
    //      we have to dig through all the annotations in the project, find any that fall into this "multi-value
    //      constraint" category, and include them in our calculations.
    for (Class<? extends Annotation> annotationClass : reflections.getSubTypesOf(Annotation.class)) {
        if (isMultiValueConstraintClass(annotationClass))
            constraintAnnotationClasses.add(annotationClass);
    }

    // Setup the master constraint list
    allConstraintAnnotationsMasterList =
        new ArrayList<>(setupAllConstraintAnnotationsMasterList(reflections, constraintAnnotationClasses));

    /*
     * Finally use the info we've gathered/constructed previously to populate the
     * {@link #projectRelevantConstraintAnnotationsExcludingUnitTestsList} field, which is the main chunk of data
     * that extensions of this class will care about.
     */
    projectRelevantConstraintAnnotationsExcludingUnitTestsList = Collections.unmodifiableList(
        getSubAnnotationListUsingExclusionFilters(allConstraintAnnotationsMasterList,
                                                  ignoreAllAnnotationsAssociatedWithTheseClasses,
                                                  specificAnnotationDeclarationsExcludedFromStrictMessageRequirement));
}
项目:FinanceAnalytics    文件:OpenGammaFudgeContext.java   
private static FudgeContext constructContext() {
  FudgeContext fudgeContext = new FudgeContext();
  ExtendedFudgeBuilderFactory.init(fudgeContext.getObjectDictionary());
  InnerClassFudgeBuilderFactory.init(fudgeContext.getObjectDictionary());

  // hack to handle non-existent classpath directory entries
  List<UrlType> urlTypes = Lists.newArrayList(Vfs.getDefaultUrlTypes());
  urlTypes.add(0, new OGFileUrlType());
  Vfs.setDefaultURLTypes(urlTypes);

  // init annotation reflector, which needs this class loader
  Set<ClassLoader> loaders = new HashSet<>();
  loaders.add(OpenGammaFudgeContext.class.getClassLoader());
  try {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader != null) {
      loaders.add(loader);
    }
  } catch (Exception ex) {
    // ignore
  }

  int availableProcessors = Runtime.getRuntime().availableProcessors();
  ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("Reflections-scan-%d").build();
  ExecutorService executorService = Executors.newFixedThreadPool(availableProcessors, factory);

  try {
    Configuration config = new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forManifest(ClasspathHelper.forJavaClassPath()))
      .setScanners(new TypeAnnotationsScanner(), new FieldAnnotationsScanner(), new SubTypesScanner(false))
      .filterInputsBy(FilterBuilder.parse(AnnotationReflector.DEFAULT_ANNOTATION_REFLECTOR_FILTER))
      .addClassLoaders(loaders)
      .setExecutorService(executorService);

    AnnotationReflector.initDefaultReflector(new AnnotationReflector(config));
    AnnotationReflector reflector = AnnotationReflector.getDefaultReflector();

    fudgeContext.getObjectDictionary().addAllAnnotatedBuilders(reflector);
    fudgeContext.getTypeDictionary().addAllAnnotatedSecondaryTypes(reflector);
  } finally {
    executorService.shutdown();
  }

  FudgeTypeDictionary td = fudgeContext.getTypeDictionary();
  td.registerClassRename("com.opengamma.util.timeseries.zoneddatetime.ArrayZonedDateTimeDoubleTimeSeries", ImmutableZonedDateTimeDoubleTimeSeries.class);
  td.registerClassRename("com.opengamma.timeseries.zoneddatetime.ArrayZonedDateTimeDoubleTimeSeries", ImmutableZonedDateTimeDoubleTimeSeries.class);
  td.registerClassRename("com.opengamma.util.timeseries.zoneddatetime.ListZonedDateTimeDoubleTimeSeries", ImmutableZonedDateTimeDoubleTimeSeries.class);
  td.registerClassRename("com.opengamma.timeseries.zoneddatetime.ListZonedDateTimeDoubleTimeSeries", ImmutableZonedDateTimeDoubleTimeSeries.class);

  td.registerClassRename("com.opengamma.util.timeseries.localdate.ArrayLocalDateDoubleTimeSeries", ImmutableLocalDateDoubleTimeSeries.class);
  td.registerClassRename("com.opengamma.timeseries.localdate.ArrayLocalDateDoubleTimeSeries", ImmutableLocalDateDoubleTimeSeries.class);
  td.registerClassRename("com.opengamma.util.timeseries.localdate.ListLocalDateDoubleTimeSeries", ImmutableLocalDateDoubleTimeSeries.class);
  td.registerClassRename("com.opengamma.timeseries.localdate.ListLocalDateDoubleTimeSeries", ImmutableLocalDateDoubleTimeSeries.class);
  td.registerClassRename("com.opengamma.util.timeseries.localdate.MapLocalDateDoubleTimeSeries", ImmutableLocalDateDoubleTimeSeries.class);
  td.registerClassRename("com.opengamma.timeseries.localdate.MapLocalDateDoubleTimeSeries", ImmutableLocalDateDoubleTimeSeries.class);

  td.registerClassRename("com.opengamma.id.Identifier", ExternalId.class);
  td.registerClassRename("com.opengamma.id.IdentifierBundleWithDates", ExternalIdBundleWithDates.class);
  td.registerClassRename("com.opengamma.id.IdentifierBundle", ExternalIdBundle.class);
  td.registerClassRename("com.opengamma.id.IdentifierWithDates", ExternalIdWithDates.class);
  td.registerClassRename("com.opengamma.id.ObjectIdentifier", ObjectId.class);
  td.registerClassRename("com.opengamma.id.UniqueIdentifier", UniqueId.class);
  return fudgeContext;
}
项目:anno4j    文件:OWLSchemaPersistingManagerTest.java   
@Test
public void testAnnotationPersisting() throws Exception {
    Anno4j anno4j = new Anno4j();

    Reflections types = new Reflections(
            new ConfigurationBuilder()
            .setUrls(
                    ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()),
                    ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader())
            )
            .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner())
    );

    Transaction transaction = anno4j.createTransaction();
    transaction.begin();
    SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection());

    persistingManager.persistSchema(types);

    // Query property characteristics:
    String q = QUERY_PREFIX + "ASK { " +
            "   <http://example.de/#id> a owl:FunctionalProperty . " +
            "   <http://example.de/#id> a owl:InverseFunctionalProperty . " +
            "   <http://example.de/#partner> a owl:SymmetricProperty . " +
            "   <http://example.de/#has_subordinate> a owl:TransitiveProperty . " +
            "   <http://example.de/#has_boss> a owl:TransitiveProperty . " +
            "   <http://example.de/#has_boss> owl:inverseOf <http://example.de/#has_subordinate> . " +
            "   <http://example.de/#has_subordinate> owl:inverseOf <http://example.de/#has_boss> . " +
            "}";
    BooleanQuery characteristicsQuery = transaction.getConnection().prepareBooleanQuery(QueryLanguage.SPARQL, q);
    assertTrue(characteristicsQuery.evaluate());

    // Query property restrictions:
    q = QUERY_PREFIX + "ASK { " +
            "   ?r1 a owl:Restriction . " +
            "   <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r1 . " +
            "   ?r1 owl:onProperty <http://example.de/#id> . " +
            "   ?r1 owl:minCardinality ?v1 . " +
            "   FILTER ( ?v1 = 1 )" +

            "   ?r2 a owl:Restriction . " +
            "   <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r2 . " +
            "   ?r2 owl:onProperty <http://example.de/#id> . " +
            "   ?r2 owl:maxCardinality ?v2 . " +
            "   FILTER ( ?v2 = 1 )" +

            "   ?r3 a owl:Restriction . " +
            "   <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r3 . " +
            "   ?r3 owl:onProperty <http://example.de/#partner> . " +
            "   ?r3 owl:onClass <http://example.de/#validly_annotated_person> . " +
            "   ?r3 owl:minQualifiedCardinality ?v3 . " +
            "   FILTER ( ?v3 = 0 )" +

            "   ?r4 a owl:Restriction . " +
            "   <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r4 . " +
            "   ?r4 owl:onProperty <http://example.de/#has_boss> . " +
            "   ?r4 owl:allValuesFrom <http://example.de/#validly_annotated_person> . " +

            "   ?r5 a owl:Restriction . " +
            "   <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r5 . " +
            "   ?r5 owl:onProperty <http://example.de/#has_activity> . " +
            "   ?r5 owl:minCardinality ?v5 . " +
            "   FILTER( ?v5 = 2 )" +

            "   ?r6 a owl:Restriction . " +
            "   <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r6 . " +
            "   ?r6 owl:onProperty <http://example.de/#has_activity> . " +
            "   ?r6 owl:minQualifiedCardinality ?v6 . " +
            "   ?r6 owl:onClass <http://example.de/#job> . " +
            "   FILTER( ?v6 = 1 )" +
            "}";

    BooleanQuery restrictionQuery = transaction.getConnection().prepareBooleanQuery(QueryLanguage.SPARQL, q);
    assertTrue(restrictionQuery.evaluate());
}
项目:cosmo    文件:TypesFinder.java   
public TypesFinder(){
    reflections = new Reflections(new FieldAnnotationsScanner(), 
                                    new MethodAnnotationsScanner(), 
                                    new TypeAnnotationsScanner(), 
                                    new SubTypesScanner());
}