Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I guess I can't do it using the reflections library. So I did it by hand:</p> <pre><code>public static List&lt;Class&lt;?&gt;&gt; getClassesAnnotatedWith(Class annotation, ServletContext servletContext) { List&lt;Class&lt;?&gt;&gt; webClasses, jarClasses; webClasses= getClassesAnnotedWithFromClassLoader(annotation, servletContext.getClassLoader()); jarClasses= getClassesAnnotedWithFromClassLoader(annotation, Thread.currentThread().getContextClassLoader()); for (Class&lt;?&gt; jarClass : jarClasses) { Class&lt;?&gt; elementToAdd= null; for (Class&lt;?&gt; webClass : webClasses) { if ( ! jarClass.getName().equals(webClass.getName())) { elementToAdd= jarClass; } } if(elementToAdd != null) { webClasses.add(elementToAdd); } } return webClasses; } private static List&lt;Class&lt;?&gt;&gt; getClassesAnnotedWithFromClassLoader(Class annotation, ClassLoader classLoader) { List&lt;Class&lt;?&gt;&gt; classes= new ArrayList&lt;Class&lt;?&gt;&gt;(); Class&lt;?&gt; classLoaderClass= classLoader.getClass(); while (! classLoaderClass.getName().equals("java.lang.ClassLoader")) { classLoaderClass= classLoaderClass.getSuperclass(); } try { Field fldClasses= classLoaderClass.getDeclaredField("classes"); fldClasses.setAccessible(true); Vector&lt;Class&lt;?&gt;&gt; classesVector= (Vector&lt;Class&lt;?&gt;&gt;) fldClasses.get(classLoader); for (Class c : classesVector) { if (c.isAnnotationPresent(annotation)) { classes.add(c); } } } catch (Exception e) { } return classes; } </code></pre> <p>I get the ClassLoader from my WAR package through the ServletContext object. There is also a protection in case a class is defined in both the WAR and the JAR with the annotation and same name (you should probably check if the packages are the same too though).</p> <p>Note that you should probably never use this code in your own projects (maybe only for debugging). It involves reflecting the ClassLoader class to make the "classes" property public. This property might not exists in Java 9 for example, so beware. This might also have some security problems if you are interacting modules written by third parties.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload