blob: 83100bc6050b33cbddeb93e669431f29bee29f2b [file] [log] [blame]
Michael Hanlca740d72015-06-16 10:04:58 +02001package de.ids_mannheim.korap.config;
2
3import org.reflections.Reflections;
4
Michael Hanlbadd79c2015-06-19 07:41:03 +02005import java.lang.annotation.Annotation;
Michael Hanlc4446022016-02-12 18:03:17 +01006import java.lang.reflect.ParameterizedType;
7import java.lang.reflect.Type;
Michael Hanlca740d72015-06-16 10:04:58 +02008import java.util.Set;
9
10/**
11 * @author hanl
12 * @date 10/06/2015
13 */
14public class KustvaktClassLoader {
15
16 private static final Reflections reflections = new Reflections(
17 "de.ids_mannheim.korap");
18
Michael Hanl8abaf9e2016-05-23 16:46:35 +020019
20 private KustvaktClassLoader () {}
21
Michael Hanl19390652016-01-16 11:01:24 +010022
Michael Hanlca740d72015-06-16 10:04:58 +020023 /**
24 * loads interface implementations in current classpath
Michael Hanl8abaf9e2016-05-23 16:46:35 +020025 *
Michael Hanlca740d72015-06-16 10:04:58 +020026 * @param iface
27 * @param <T>
28 * @return
29 */
Michael Hanl8abaf9e2016-05-23 16:46:35 +020030 public static <T> Set<Class<? extends T>> loadSubTypes (Class<T> iface) {
Michael Hanlca740d72015-06-16 10:04:58 +020031 return reflections.getSubTypesOf(iface);
32 }
Michael Hanlbadd79c2015-06-19 07:41:03 +020033
Michael Hanl8abaf9e2016-05-23 16:46:35 +020034
35 public static Set<Class<?>> loadFromAnnotation (
Michael Hanlbadd79c2015-06-19 07:41:03 +020036 Class<? extends Annotation> annotation) {
37 return reflections.getTypesAnnotatedWith(annotation);
38 }
Michael Hanlc4446022016-02-12 18:03:17 +010039
Michael Hanl8abaf9e2016-05-23 16:46:35 +020040
41 public static <T> Class<? extends T> getTypeClass (Class type,
42 Class<T> iface) {
Michael Hanl88b49db2016-02-16 17:15:43 +010043 Set<Class<? extends T>> c = KustvaktClassLoader.loadSubTypes(iface);
44 for (Class<? extends T> o : c) {
Michael Hanlc4446022016-02-12 18:03:17 +010045 Type ctype = o.getGenericInterfaces()[0];
46 if (ctype instanceof ParameterizedType) {
47 ParameterizedType ptype = (ParameterizedType) ctype;
48 Class tclass = (Class) ptype.getActualTypeArguments()[0];
49 if (tclass.equals(type))
50 return o;
51 }
52 }
53 return null;
54 }
Michael Hanlca740d72015-06-16 10:04:58 +020055}