본문 바로가기

Development/Programming

[Java] 패키지 탐색하기~!

Java에서 Reflection을 편리하게? 사용하기 위한 라이브러리가 있다. 아래와 같이 사용하면 된다.~!


1. 라이브러리 추가

<dependency>
     
<groupId>org.reflections</groupId>
     
<artifactId>reflections</artifactId>
     
<version>0.9.9-RC1</version>
</dependency>


2. 사용법

Reflections reflections = new Reflections("my.project.prefix");

     
Set<Class<? extends SomeType>> subTypes =
               reflections
.getSubTypesOf(SomeType.class);

     
Set<Class<?>> annotated =
               reflections
.getTypesAnnotatedWith(SomeAnnotation.class);


 Reflections reflections = new Reflections("my.package.prefix");
     
//or
     
Reflections reflections = new Reflections(ClasspathHelper.forPackage("my.package.prefix"),
         
new SubTypesScanner(), new TypesAnnotationScanner(), new FilterBuilder().includePackage(...), ...);

     
//or using the ConfigurationBuilder
     
new Reflections(new ConfigurationBuilder()
         
.filterInputsBy(new FilterBuilder().includePackage("my.project.prefix"))
         
.setUrls(ClasspathHelper.forPackage("my.project.prefix"))
         
.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...));

     
//then query, for example:
     
Set<Class<? extends Module>> modules = reflections.getSubTypesOf(com.google.inject.Module.class);
     
Set<Class<?>> singletons =             reflections.getTypesAnnotatedWith(javax.inject.Singleton.class);
     
     
Set<String> properties =       reflections.getResources(Pattern.compile(".*\\.properties"));
     
Set<Constructor> injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class);
     
Set<Method> deprecateds =      reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class);
     
Set<Field> ids =               reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);

     
Set<Method> someMethods =      reflections.getMethodsMatchParams(long.class, int.class);
     
Set<Method> voidMethods =      reflections.getMethodsReturn(void.class);
     
Set<Method> pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class);
     
Set<Method> floatToString =    reflections.getConverters(Float.class, String.class);


'Development > Programming' 카테고리의 다른 글

[Java] wait, notify, notifyAll  (0) 2014.05.16
[Java] synchronized 사용법 정리  (0) 2014.05.16
[Scala] Named Parameters  (0) 2014.04.15
[Java] Class Method 접근 및 사용  (0) 2014.04.09
[Scala] Generic Classes  (0) 2014.03.28