Last active
May 11, 2017 09:50
-
-
Save nuria/d611afcb9f49d30252b58429305a3d04 to your computer and use it in GitHub Desktop.
Snippet to get classes belonging to a package at runtime that have a certain annotation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package org.wikimedia.analytics.refinery.tag; | |
| import com.google.common.collect.ImmutableSet; | |
| import com.google.common.reflect.ClassPath; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| import java.util.Set; | |
| import org.reflections.*; | |
| import java.util.Iterator; | |
| public class TagChain { | |
| List<String> tags = new ArrayList<String>(); | |
| List<Tagger> chain = new ArrayList<Tagger>(); | |
| public TagChain() throws Exception { | |
| // now get all classes that are part of this chain | |
| // scan annotations at runtime and build it | |
| // or get it from package | |
| ClassLoader loader = this.getClass().getClassLoader(); | |
| ClassPath p = ClassPath.from(loader); | |
| ImmutableSet<ClassPath.ClassInfo> listOfClasses = | |
| p.getTopLevelClasses("org.wikimedia.analytics.refinery.tag.impl"); | |
| for( ClassPath.ClassInfo ci:listOfClasses) { | |
| Class<?> clazz = Class.forName(ci.getName()) ; | |
| chain.add((Tagger) clazz.newInstance()); | |
| } | |
| Reflections reflections = new Reflections("org.wikimedia.analytics.refinery.tag.impl"); | |
| Set<Class<?>> taggerClasses = reflections.getTypesAnnotatedWith(org.wikimedia.analytics.refinery.tag.Tag.class); | |
| System.out.println(taggerClasses); | |
| for(Class taggerClass:taggerClasses){ | |
| Class<?> clazz = Class.forName(taggerClass.getName()); | |
| System.out.println(taggerClass.getName()); | |
| chain.add((Tagger) clazz.newInstance()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment