Java Code Examples for org.reflections.Reflections

The following examples show how to use org.reflections.Reflections. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: smart-admin   Source File: DataScopeSqlConfigService.java    License: MIT License 7 votes vote down vote up
/**
 * 刷新 所有添加数据范围注解的接口方法配置<class.method,DataScopeSqlConfigDTO></>
 *
 * @return
 */
private Map<String, DataScopeSqlConfigDTO> refreshDataScopeMethodMap() {
    Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(scanPackage)).setScanners(new MethodAnnotationsScanner()));
    Set<Method> methods = reflections.getMethodsAnnotatedWith(DataScope.class);
    for (Method method : methods) {
        DataScope dataScopeAnnotation = method.getAnnotation(DataScope.class);
        if (dataScopeAnnotation != null) {
            DataScopeSqlConfigDTO configDTO = new DataScopeSqlConfigDTO();
            configDTO.setDataScopeType(dataScopeAnnotation.dataScopeType().getType());
            configDTO.setJoinSql(dataScopeAnnotation.joinSql());
            configDTO.setWhereIndex(dataScopeAnnotation.whereIndex());
            dataScopeMethodMap.put(method.getDeclaringClass().getSimpleName() + "." + method.getName(), configDTO);
        }
    }
    return dataScopeMethodMap;
}
 
Example 2
Source Project: usergrid   Source File: SetupDao.java    License: Apache License 2.0 7 votes vote down vote up
public void setup() throws IOException, NoSuchFieldException, IllegalAccessException {
    String key;
    CreateIndexResponse ciResp;

    Reflections reflections = new Reflections("org.apache.usergrid.chop.webapp.dao");
    Set<Class<? extends Dao>> daoClasses = reflections.getSubTypesOf(Dao.class);

    IndicesAdminClient client = elasticSearchClient.getClient().admin().indices();

    for (Class<? extends Dao> daoClass : daoClasses) {

        key = daoClass.getDeclaredField("DAO_INDEX_KEY").get(null).toString();

        if (!client.exists(new IndicesExistsRequest(key)).actionGet().isExists()) {
            ciResp = client.create(new CreateIndexRequest(key)).actionGet();
            if (ciResp.isAcknowledged()) {
                LOG.debug("Index for key {} didn't exist, now created", key);
            } else {
                LOG.debug("Could not create index for key: {}", key);
            }
        } else {
            LOG.debug("Key {} already exists", key);
        }
    }
}
 
Example 3
Source Project: gauge-java   Source File: StepsScannerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildStepRegistryUpdatesReflectedMethod() {
    HashSet<Method> steps = new HashSet<>();
    steps.add(method2);
    String expectedMethodName = method2.getName();

    StepRegistryEntry entry = new StepRegistryEntry();
    entry.setFullyQualifiedName(method2.getName()); // simulate static scan of this method

    Reflections reflections = mock(Reflections.class);
    when(reflections.getMethodsAnnotatedWith(Step.class)).thenReturn(steps);

    StepRegistry registry = mock(StepRegistry.class);
    String stepTemplateText = "hello world {}";
    when(registry.contains(stepTemplateText)).thenReturn(true);
    when(registry.getForCurrentProject(stepTemplateText, method2)).thenReturn(entry);

    new StepsScanner(registry).scan(reflections);

    assertNotNull(entry.getMethodInfo());
    assertEquals(expectedMethodName, entry.getMethodInfo().getName());
}
 
Example 4
Source Project: FontVerter   Source File: FontVerter.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void registerFontAdapters() {
    synchronized (adapterLock) {
        if (adapters == null) {
            Reflections reflections = new Reflections("org.mabb.fontverter");
            Set<Class<? extends FVFont>> adapterClasses = reflections.getSubTypesOf(FVFont.class);
            Class[] adapterArr = adapterClasses.toArray(new Class[adapterClasses.size()]);
            adapters = Arrays.asList(adapterArr);

            // CFF always last to try
            Class cffAdapter = null;
            for (Class adapterOn : adapters) {
                if (adapterOn.getSimpleName().contains("CffFont"))
                    cffAdapter = adapterOn;
            }

            int cffIndex = adapters.indexOf(cffAdapter);
            adapters.set(cffIndex, adapters.get(adapters.size() - 1));
            adapters.set(adapters.size() - 1, cffAdapter);

            adapters = removeAbstractClasses(adapters);
        }
    }
}
 
Example 5
Source Project: drftpd   Source File: DiskSelectionFilter.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void initFilters() {
    CaseInsensitiveHashMap<String, Class<? extends DiskFilter>> filtersMap = new CaseInsensitiveHashMap<>();
    // TODO [DONE] @k2r Load Filters
    Set<Class<? extends DiskFilter>> aFilters = new Reflections("org.drftpd")
            .getSubTypesOf(DiskFilter.class);
    List<Class<? extends DiskFilter>> filters = aFilters.stream()
            .filter(aClass -> !Modifier.isAbstract(aClass.getModifiers())).collect(Collectors.toList());
    try {
        for (Class<? extends DiskFilter> filterClass : filters) {
            String filterName = filterClass.getSimpleName().replace("Filter", "");
            filtersMap.put(filterName, filterClass);
        }
    } catch (Exception e) {
        logger.error("Failed to load plugins for slave extension point 'Handler', possibly the slave"
                + " extension point definition has changed in the plugin.xml", e);
    }
    _filtersMap = filtersMap;
}
 
Example 6
Source Project: flink   Source File: StateHandleSerializationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void ensureStateHandlesHaveSerialVersionUID() {
	try {
		Reflections reflections = new Reflections("org.apache.flink");

		// check all state handles

		@SuppressWarnings("unchecked")
		Set<Class<?>> stateHandleImplementations = (Set<Class<?>>) (Set<?>)
				reflections.getSubTypesOf(StateObject.class);

		for (Class<?> clazz : stateHandleImplementations) {
			validataSerialVersionUID(clazz);
		}
	}
	catch (Exception e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 7
@BeforeClass
public static void before(){

    //Collect all classes implementing TextConfig interface (i.e., has JSON and YAML conversion support)

    Reflections reflections = new Reflections("ai.konduit");
    Set<Class<? extends TextConfig>> subTypes = reflections.getSubTypesOf(TextConfig.class);

    System.out.println(String.format("All subtypes of %s:", TextConfig.class.getCanonicalName()));
    for(Class<? extends TextConfig> c : subTypes ){
        int mod = c.getModifiers();
        if(Modifier.isAbstract(mod) || Modifier.isInterface(mod))
            continue;
        allClasses.add(c);
        System.out.println(c);
    }
}
 
Example 8
Source Project: gauge-java   Source File: CustomScreenshotScanner.java    License: Apache License 2.0 6 votes vote down vote up
public void scan(Reflections reflections) {
    Set<Class<? extends ICustomScreenshotGrabber>> customScreenshotGrabbers = reflections.getSubTypesOf(ICustomScreenshotGrabber.class);

    if (customScreenshotGrabbers.size() > 0) {
        Class<? extends ICustomScreenshotGrabber> customScreenGrabber = customScreenshotGrabbers.iterator().next();
        Logger.debug(String.format("Using %s as custom screenshot grabber", customScreenGrabber.getName()));
        ScreenshotFactory.setCustomScreenshotGrabber(customScreenGrabber);
    }

    Set<Class<? extends CustomScreenshotWriter>> customScreenshotWriters = reflections.getSubTypesOf(CustomScreenshotWriter.class);

    if (customScreenshotWriters.size() > 0) {
        Class<? extends CustomScreenshotWriter> customScreenWriter = customScreenshotWriters.iterator().next();
        Logger.debug(String.format("Using %s as custom screenshot grabber", customScreenWriter.getName()));
        ScreenshotFactory.setCustomScreenshotGrabber(customScreenWriter);
    }
}
 
Example 9
Source Project: mjprof   Source File: PluginUtils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public static HashMap<Class, Class> getAllPlugins() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, ClassNotFoundException {
  HashMap<Class, Class> map = new HashMap<>();
  //TODO
  Reflections reflections = new Reflections("com.performizeit");
  Set<Class<?>> annotatedPlugin = reflections.getTypesAnnotatedWith(Plugin.class);

  for (Class cla : annotatedPlugin) {
    if (BasePlugin.class.isAssignableFrom(cla)) {
      invokeGetHelpLine(cla);
      map.put(cla, cla);
    } else {
      System.out.println("ERROR: class " + cla.getName() + " needs to extend BasePlugin child");
    }
  }
  return map;
}
 
Example 10
Source Project: disconf   Source File: ScanPrinterUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 打印出StoreMap的数据
 */
public static void printStoreMap(Reflections reflections) {

    LOGGER.info("Now we will print store map......");

    Store store = reflections.getStore();
    Map<String/* indexName */, Multimap<String, String>> storeMap = store.getStoreMap();
    for (String indexName : storeMap.keySet()) {

        LOGGER.info("====================================");
        LOGGER.info("indexName:" + indexName);

        Multimap<String, String> multimap = storeMap.get(indexName);

        for (String firstName : multimap.keySet()) {
            Collection<String> lastNames = multimap.get(firstName);
            LOGGER.info("\t\t" + firstName + ": " + lastNames);
        }

    }
}
 
Example 11
Source Project: streams   Source File: StreamsJacksonModule.java    License: Apache License 2.0 6 votes vote down vote up
public StreamsJacksonModule() {
  super();

  Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("org.apache.streams.jackson"))
      .setScanners(new SubTypesScanner()));

  Set<Class<? extends StreamsDateTimeFormat>> dateTimeFormatClasses = reflections.getSubTypesOf(StreamsDateTimeFormat.class);

  List<String> dateTimeFormats = new ArrayList<>();
  for (Class dateTimeFormatClass : dateTimeFormatClasses) {
    try {
      dateTimeFormats.add(((StreamsDateTimeFormat) (dateTimeFormatClass.newInstance())).getFormat());
    } catch (Exception ex) {
      LOGGER.warn("Exception getting format from " + dateTimeFormatClass);
    }
  }

  addSerializer(DateTime.class, new StreamsDateTimeSerializer(DateTime.class));
  addDeserializer(DateTime.class, new StreamsDateTimeDeserializer(DateTime.class, dateTimeFormats));

  addSerializer(Period.class, new StreamsPeriodSerializer(Period.class));
  addDeserializer(Period.class, new StreamsPeriodDeserializer(Period.class));
}
 
Example 12
Source Project: Alink   Source File: AnnotationUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Map<String, Wrapper<BaseDB>> loadDBClasses() {
    Reflections reflections = new Reflections("com.alibaba.alink");
    Map<String, Wrapper<BaseDB>> map = new HashMap<>();
    Set<Class<?>> set = reflections.getTypesAnnotatedWith(DBAnnotation.class);
    for (Class<?> clazz : set) {
        if (!BaseDB.class.isAssignableFrom(clazz)) {
            LOG.error("DB class annotated with @DBAnnotation should be subclass of BaseDB: {}",
                    clazz.getCanonicalName());
            continue;
        }

        DBAnnotation annotation = clazz.getAnnotation(DBAnnotation.class);
        String name = annotation.name();
        boolean hasTimestamp = annotation.hasTimestamp();
        Wrapper<BaseDB> origin = map.put(name, new Wrapper<>((Class<? extends BaseDB>) clazz, hasTimestamp));
        if (origin != null) {
            LOG.error("Multiple DB class with same name {}: {} and {}",
                    name, origin.clazz.getCanonicalName(), clazz.getCanonicalName());
        }
    }

    return ImmutableMap.copyOf(map);
}
 
Example 13
public GnarlyGenotyperEngine(final boolean keepAllSites, final int maxAltAllelesToOutput, final boolean summarizePls, final boolean stripASAnnotations) {
    this.maxAltAllelesToOutput = maxAltAllelesToOutput;
    this.summarizePls = summarizePls;
    this.keepAllSites = keepAllSites;
    this.stripASAnnotations = stripASAnnotations;

    if (!summarizePls) {
        final GenotypeLikelihoodCalculators GLCprovider = new GenotypeLikelihoodCalculators();

        //initialize PL size cache -- HTSJDK cache only goes up to 4 alts, but I need 6
        likelihoodSizeCache = new int[maxAltAllelesToOutput + 1 + 1]; //+1 for ref and +1 so index == numAlleles
        glcCache.add(null); //add a null at index zero because zero alleles (incl. ref) makes no sense
        for (final int numAlleles : IntStream.rangeClosed(1, maxAltAllelesToOutput + 1).boxed().collect(Collectors.toList())) {
            likelihoodSizeCache[numAlleles] = GenotypeLikelihoods.numLikelihoods(numAlleles, ASSUMED_PLOIDY);
            //GL calculator cache is indexed by the total number of alleles, including ref
            glcCache.add(numAlleles, GLCprovider.getInstance(ASSUMED_PLOIDY, numAlleles));
        }
    }

    //TODO: fix weird reflection logging?
    final Reflections reflections = new Reflections("org.broadinstitute.hellbender.tools.walkers.annotator.allelespecific");
    allASAnnotations = reflections.getSubTypesOf(InfoFieldAnnotation.class);
    allASAnnotations.addAll(reflections.getSubTypesOf(AS_StrandBiasTest.class));
    allASAnnotations.addAll(reflections.getSubTypesOf(AS_RankSumTest.class));
}
 
Example 14
Source Project: java-flagz   Source File: ScalaObjectScanner.java    License: MIT License 6 votes vote down vote up
static synchronized Set<Object> scanFlagObjects(List<String> packagePrefixes) {

    Reflections reflections = ReflectionsCache.reflectionsForPrefixes(packagePrefixes);
    Set<Object> objects = new HashSet<>();
    for (Class<?> clazz : reflections.getSubTypesOf(FlagContainer.class)) {
      checkDelayedInit(clazz);
      // Scala objects have a MODULE$ static field.
      // http://grahamhackingscala.blogspot.co.uk/2009/11/scala-under-hood-of-hello-world.html
      try {
        Field staticModuleField = clazz.getDeclaredField("MODULE$");
        boolean wasAccessible = staticModuleField.isAccessible();
        if (!wasAccessible) {
          staticModuleField.setAccessible(true);
        }
        objects.add(staticModuleField.get(null));  // null is fine, this is a static field.
        staticModuleField.setAccessible(wasAccessible);
      } catch (NoSuchFieldException | IllegalAccessException exception) {
        throw new IllegalArgumentException(
            "Error reflecting on Scala object. " + clazz.getCanonicalName(), exception);
      }
    }
    return objects;
  }
 
Example 15
Source Project: gauge-java   Source File: StepsScannerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildStepRegistryForExternalReference() {
    HashSet<Method> steps = new HashSet<>();
    steps.add(method2);

    Reflections reflections = mock(Reflections.class);
    when(reflections.getMethodsAnnotatedWith(Step.class)).thenReturn(steps);

    StepRegistry registry = mock(StepRegistry.class);
    String stepTemplateText = "hello world {}";
    when(registry.contains(stepTemplateText)).thenReturn(false);

    new StepsScanner(registry).scan(reflections);

    ArgumentCaptor<StepValue> stepValueArgumentCaptor = ArgumentCaptor.forClass(StepValue.class);
    ArgumentCaptor<Method> methodArgumentCaptor = ArgumentCaptor.forClass(Method.class);
    ArgumentCaptor<Boolean> booleanArgumentCaptor = ArgumentCaptor.forClass(Boolean.class);

    verify(registry, times(1)).addStepImplementation(stepValueArgumentCaptor.capture(), methodArgumentCaptor.capture(), booleanArgumentCaptor.capture());

    assertEquals(stepTemplateText, stepValueArgumentCaptor.getValue().getStepText());
    assertEquals(method2, methodArgumentCaptor.getValue());
    assertTrue(booleanArgumentCaptor.getValue());
}
 
Example 16
Source Project: mybatis-jpa   Source File: AnnotationStatementScanner.java    License: Apache License 2.0 6 votes vote down vote up
public void scan() {
  for (String basePackage : basePackages) {
    Reflections reflections = new Reflections(basePackage, new TypeAnnotationsScanner(),
        new SubTypesScanner(), new MethodAnnotationsScanner());
    Set<Class<?>> mappers = reflections.getTypesAnnotatedWith(Mapper.class);
    for (Class<?> mapperClass : mappers) {
      Method[] methods = mapperClass.getMethods();
      for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
          StatementFactory statementFactory = annotationStatementRegistry
              .findFactory(annotation.annotationType());
          if (statementFactory != null) {
            MappedStatement statement = statementFactory.parseStatement(configuration, method, mapperClass);
            configuration.addMappedStatement(statement);
          }
        }

      }
    }
  }
  parsePendingMethods();
}
 
Example 17
Source Project: rice   Source File: StaticWeavingTest.java    License: Educational Community License v2.0 5 votes vote down vote up
@Test
public void testStaticWeaving() {
    // first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
    Reflections reflections = new Reflections(getClass().getPackage().getName());
    Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
    Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);

    // next, let's assert that they have been statically weaved
    assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
 
Example 18
Source Project: arangodb-java-driver   Source File: NativeImageHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static void generateReflectConfig() throws JsonProcessingException {
    System.out.println("---------------------------");
    System.out.println("--- reflect-config.json ---");
    System.out.println("---------------------------");

    List<String> packages = Arrays.asList("com.arangodb.entity", "com.arangodb.model");

    ObjectMapper mapper = new ObjectMapper();
    ArrayNode rootNode = mapper.createArrayNode();
    ObjectNode noArgConstructor = mapper.createObjectNode();
    noArgConstructor.put("name", "<init>");
    noArgConstructor.set("parameterTypes", mapper.createArrayNode());
    ArrayNode methods = mapper.createArrayNode();
    methods.add(noArgConstructor);

    packages.stream()
            .flatMap(p -> {
                final ConfigurationBuilder config = new ConfigurationBuilder()
                        .setScanners(new ResourcesScanner(), new SubTypesScanner(false))
                        .setUrls(ClasspathHelper.forPackage(p))
                        .filterInputsBy(new FilterBuilder().includePackage(p));

                return new Reflections(config).getSubTypesOf(Object.class).stream();
            })
            .map(Class::getName)
            .map(className -> {
                ObjectNode entry = mapper.createObjectNode();
                entry.put("name", className);
                entry.put("allDeclaredFields", true);
                entry.set("methods", methods);
                return entry;
            })
            .forEach(rootNode::add);

    String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
    System.out.println(jsonString);
}
 
Example 19
Source Project: drftpd   Source File: SiteBot.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void loadListeners() {
    List<ListenerInterface> listeners = new ArrayList<>();
    // TODO [DONE] @k2r Load sitebot listeners
    Set<Class<? extends ListenerInterface>> sitebotListeners = new Reflections("org.drftpd")
            .getSubTypesOf(ListenerInterface.class);
    try {
        for (Class<? extends ListenerInterface> sitebotListener : sitebotListeners) {
            ListenerInterface listener = sitebotListener.getConstructor().newInstance();
            listeners.add(listener);
        }
    } catch (Exception e) {
        logger.error("Failed to load plugins for org.drftpd.master.plugins.sitebot extension point 'Listener', possibly the " + "org.drftpd.master.plugins.sitebot extension point definition has changed in the plugin.xml", e);
    }
    _listeners = listeners;
}
 
Example 20
Source Project: cukes   Source File: SingletonObjectFactory.java    License: Apache License 2.0 5 votes vote down vote up
private void addExternalModules() {
    Reflections reflections = new Reflections("lv.ctco.cukes");
    for (Class targetClass : reflections.getTypesAnnotatedWith(CukesInjectableModule.class)) {
        try {
            Constructor<Module> constructor = targetClass.getConstructor();
            Module module = constructor.newInstance();
            addModule(module);
        } catch (Exception e) {
            throw new CukesRuntimeException("Unable to add External Module to Guice");
        }
    }
}
 
Example 21
Source Project: chassis   Source File: ConfigurationBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public ConfigurationBuilder(String appName, String appEnvironment, boolean addSystemConfigs, Reflections reflections) {
    Preconditions.checkArgument(StringUtils.isNotBlank(appName));
    Preconditions.checkArgument(StringUtils.isNotBlank(appEnvironment));
    Preconditions.checkNotNull(reflections);

    this.appName = appName;
    this.appEnvironment = appEnvironment;
    this.addSystemConfigs = addSystemConfigs;
    this.reflections = reflections;

    System.setProperty(BootstrapConfigKeys.APP_NAME_KEY.getPropertyName(), appName);
    System.setProperty(BootstrapConfigKeys.APP_ENVIRONMENT_KEY.getPropertyName(), appEnvironment);
}
 
Example 22
Source Project: kafka-connect-spooldir   Source File: TestDataUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <T extends NamedTest> List<T> loadJsonResourceFiles(String packageName, Class<T> cls) throws IOException {
    Preconditions.checkNotNull(packageName, "packageName cannot be null");
    log.info("packageName = {}", packageName);
//    Preconditions.checkState(packageName.startsWith("/"), "packageName must start with a /.");
    Reflections reflections = new Reflections(packageName, new ResourcesScanner());
    Set<String> resources = reflections.getResources(new FilterBuilder.Include("^.*\\.json$"));
    List<T> datas = new ArrayList<T>(resources.size());
    Path packagePath = Paths.get("/" + packageName.replace(".", "/"));
    for (String resource : resources) {
      log.trace("Loading resource {}", resource);
      Path resourcePath = Paths.get("/" + resource);
      Path relativePath = packagePath.relativize(resourcePath);
      File resourceFile = new File("/" + resource);
      T data;
      try (InputStream inputStream = cls.getResourceAsStream(resourceFile.getAbsolutePath())) {
        data = ObjectMapperFactory.INSTANCE.readValue(inputStream, cls);
      } catch (IOException ex) {
        if (log.isErrorEnabled()) {
          log.error("Exception thrown while loading {}", resourcePath, ex);
        }
        throw ex;
      }

      if (null != relativePath.getParent()) {
        data.path(relativePath);
      } else {
        data.path(relativePath);
      }
      datas.add(data);
    }
    return datas;
  }
 
Example 23
Source Project: jsonschema-generator   Source File: SchemaGeneratorMojo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get all the names of classes on the classpath.
 *
 * @return A set of class names as found on the classpath
 */
private Set<String> getAllClassNames() {
    if (this.allTypes == null) {
        Reflections reflections = new Reflections("", new SubTypesScanner(false), this.getClassLoader());
        allTypes = reflections.getAllTypes();
    }

    return allTypes;
}
 
Example 24
Source Project: wisp   Source File: ReflectionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过扫描,获取反射对象
 */
public static Reflections getReflection(String packName) {

    List<String> curList = new ArrayList<>();
    curList.add(packName);

    return getReflection(curList);
}
 
Example 25
Source Project: flink   Source File: CheckForbiddenMethodsUsage.java    License: Apache License 2.0 5 votes vote down vote up
public Set<Member> getUsages(Reflections reflections) {
	if (method == null) {
		return reflections.getConstructorUsage(constructor);
	}

	return reflections.getMethodUsage(method);
}
 
Example 26
Source Project: marble   Source File: HiveSqlOperatorTable.java    License: Apache License 2.0 5 votes vote down vote up
public HiveSqlOperatorTable() {
  for (SqlOperator op : operatorListOfSqlStdOperatorTable) {
    operatorMapOfSqlStdOperatorTable.put(op.getName() + "_" + op.getSyntax(),
        op);
  }
  //register hive operator
  ConfigurationBuilder builder = new ConfigurationBuilder();
  hiveFunctionPackages.add("org.apache.hadoop.hive.ql");
  builder.forPackages(hiveFunctionPackages.toArray(new String[0]));
  builder.setExpandSuperTypes(false);
  Reflections reflections = new Reflections(builder);
  registerUDF(reflections);
  registerUDAF(reflections);
}
 
Example 27
Source Project: valdr-bean-validation   Source File: ClasspathScanner.java    License: MIT License 5 votes vote down vote up
/**
 * Scans the classpath to find all classes that are in the configured model packages. It ignores excluded classes.
 *
 * @return classes to parse
 * @see Options
 */
public Set<Class<?>> findClassesToParse() {
  Reflections reflections = new Reflections(new ConfigurationBuilder().
    setUrls(buildClassLoaderUrls()).setScanners(new SubTypesScanner(false)).filterInputsBy(buildPackagePredicates()));

  return reflections.getSubTypesOf(Object.class);
}
 
Example 28
Source Project: api-boot   Source File: ClassTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化反射对象
 *
 * @param scannerPackage 扫描的package
 * @return 反射对象
 */
static Reflections initReflections(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    return new Reflections(scannerPackage);
}
 
Example 29
Source Project: bdt   Source File: CommonG.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Saves the value in the attribute in class extending CommonG.
 *
 * @param element attribute in class where to store the value
 * @param value   value to be stored
 * @throws NoSuchFieldException      exception
 * @throws SecurityException         exception
 * @throws IllegalArgumentException  exception
 * @throws IllegalAccessException    exception
 * @throws InstantiationException    exception
 * @throws ClassNotFoundException    exception
 * @throws NoSuchMethodException     exception
 * @throws InvocationTargetException exception
 */

public void setPreviousElement(String element, String value) throws
        NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
    Reflections reflections = new Reflections("com.stratio");
    Set classes = reflections.getSubTypesOf(CommonG.class);

    Object pp = (classes.toArray())[0];
    String qq = (pp.toString().split(" "))[1];
    Class<?> c = Class.forName(qq);

    Field ff = c.getDeclaredField(element);
    ff.setAccessible(true);
    ff.set(null, value);
}
 
Example 30
Source Project: rpcx-java   Source File: RpcFilterFinder.java    License: Apache License 2.0 5 votes vote down vote up
public List<Class> find() {
    Reflections reflections = new Reflections(filterPackage);
    Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(RpcFilter.class);
    List<Class> list = classesList.stream().filter(it -> {
        RpcFilter an = it.getAnnotation(RpcFilter.class);
        return Stream.of(an.group()).anyMatch(it2 -> it2.equals(group));//过滤出provider
    }).collect(Collectors.toList());
    return list.stream().sorted((a, b) -> {
        RpcFilter a1 = (RpcFilter) a.getAnnotation(RpcFilter.class);
        RpcFilter b1 = (RpcFilter) b.getAnnotation(RpcFilter.class);
        return a1.order() - b1.order();
    }).collect(Collectors.toList());
}