Class.isAssignableFrom gives wrong results in certain situation

I am really confused about the behavior. In JBoss 7, I extract all the classes with @Entity Annotation and then I need to find all of them that implement the "BusinessObject" interface.

This is the way to do it:

     private Set<Class<? extends BusinessObject>> findEntityClasses() {
        //  Alle Klassen holen, die mit "@Entity" annotiert sind. Dabei werden Hibernate- wie auch javax.persistence Annotations genommen
        Reflections reflections = new Reflections("de.something.b4");
        Set<Class<?>> entityClasses = reflections.getTypesAnnotatedWith(Entity.class);

        //Jetzt in das finale Set nur die Klassen kopieren, die von  BusinessObject erben. Weil andere benutzen wir hier nicht!
        Set<Class<? extends BusinessObject>> boClasses = new HashSet<Class<? extends BusinessObject>>();
        try {
          List<Class> l = new ArrayList<Class>(entityClasses);

          for (Class currentClass : l) {
            //Class newCurrentClass = Class.forName(currentClass.getName());
            if (BusinessObject.class.isAssignableFrom(currentClass)) {
              boClasses.add(currentClass);
            }

          }
        } catch (Throwable t) {
          System.out.println(t.getMessage());
        }

        return boClasses;
      }

      

Notice the commented line with Class.forName ()!

With this commented out, is_ssignableFrom always returns true even if currentClass does not implement BusinessObject.

As soon as I remove the comment in Class.forName (), and as soon as it calls something, it happens to that class so that all subsequent calls to isAssignableFrom return the correct value as expected.

I'm sure it has some reason and Class.forName () does something for the class or classloader, but I couldn't figure out what. Does anyone have any idea about this behavior?

+3


source to share


1 answer


Quoting from the javadoc Class.forName()

:

The call forName("X")

invokes the initialization of the named class X

.



So, if you uncomment Class.forName(currentClass.getName());

, it will initialize the class, and therefore Class.isAssignableFrom()

can test correctly if the class is BusinessObject

implemented by the class ( Reflections

may not initialize them).

0


source







All Articles