vextorspace
vextorspace

Reputation: 934

Can I use google reflections in a static section of code to find sub classes?

I am trying to set up a system that allows me to subclass a class that gets exported to a text file without having to modify the initial class. To do this, I am trying to build a list of callbacks that can tell if they handle a particular entry, and then use that callback to get an instance of that class created from the file. The problem is I get an error

java.lang.NoClassDefFoundError: com/google/common/base/Predicate when I try to run anything involving this class. What am I doing wrong?

public abstract class Visibility {

private static final List<VisibilityCreationCallback> creationCallbacks;
static {
    creationCallbacks = new ArrayList<VisibilityCreationCallback>();

    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage("com.protocase.viewer.utils.visibility"))
            .setScanners(new ResourcesScanner()));
// ... cut ...

public static Visibility importFromFile(Map<String, Object> importMap) {
   for (VisibilityCreationCallback callback: creationCallbacks) {
       if (callback.handles(importMap)) {
           return callback.create(importMap);
       }
   }

   return null;

}

public class CategoryVisibility extends Visibility{

public static VisibilityCreationCallback makeVisibilityCreationCallback () {
    return new VisibilityCreationCallback() {

        @Override
        public boolean handles(Map<String, Object> importMap) {
           return importMap.containsKey(classTag);
        }

        @Override
        public CategoryVisibility create(Map<String, Object> importMap) {
            return importPD(importMap);
        }
    };
}

/**
 * Test of matches method, of class CategoryVisibility.
 */
@Test
public void testMatches1() {
    Visibility other = new UnrestrictedVisibility();
    CategoryVisibility instance = new CategoryVisibility("A Cat");
    boolean expResult = true;
    boolean result = instance.matches(other);
    assertEquals(expResult, result);
}

Upvotes: 0

Views: 52

Answers (1)

zapp
zapp

Reputation: 1553

You're just missing the guava library in your classpath, and Reflections requires it. That's the short answer.

The better solution is to use a proper build tool (maven, gradle, ...), and have your transitive dependencies without the hassle.

Upvotes: 1

Related Questions