0

I want to find all sub classes of java.lang.Throwable in the JVM. The classes may or may not have been already loaded in the JVM.

I have read the similar question How do you find all subclasses of a given class in Java?, and I think org.reflections can solve my question.

I tried the following code:

public static void main(String[] args) {
    Reflections reflections = new Reflections( "org" ) ;
    Set<Class<? extends Throwable>> set = reflections.getSubTypesOf( Throwable.class ) ;
    for (Class<? extends Throwable> t : set) {
        System.out.println( t ) ;
    }
}

But the result is not what I expected:

class java.lang.Exception
class java.lang.RuntimeException
class org.reflections.ReflectionsException

I have two doubts:

  1. Why are java.lang.Exception and java.lang.RuntimeException in the result? I used the prefix "org".
  2. Why is java.lang.NullPointerException not in the result? It is in the package "java.lang" too.
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
Bourbon_7
  • 161
  • 7
  • You are finding direct subclasses of `Throwable`, not their subclasses. – Oliver Dec 29 '22 at 04:22
  • 1
    This is not an easy task to achieve, certainly really expensive performance wise... Can you elaborate more please on why do you need this, especially why do you need to know about throwables which are not even loaded by the JVM? – Mark Bramnik Dec 29 '22 at 07:43

1 Answers1

1
  1. The Javadoc for that Reflections library says "Reflections scans and indexes your project's classpath" so it's not looking "in the JVM", it's looking for files in your classpath and loading them with the Class Loader https://github.com/ronmamo/reflections/blob/master/src/main/java/org/reflections/Reflections.java

  2. The Javadoc for Reflections.expandSuperTypes() seems to imply that the prefix passed to Reflections is for what needs to be found, not what is scanned which has to include the supertypes in order to find your particular package targets

  3. That's why it's not listing NullPointerException because it's not scanned by expandSuperTypes() explained in #2

Mike Kim
  • 115
  • 6
  • 1
    The OP said that the result includes `java.lang.Exception` and `java.lang.RuntimeException` which contradicts the statement that the library only looks for files in the classpath. Further, I don’t see any mentioning of “prefix” in the Javadoc of `expandSuperTypes`. – Holger Jan 03 '23 at 11:13