dimanche 29 janvier 2017

I want a method to reference a class that is not available at runtime

I have a library consisting of multiple modules:

  • core
  • guava

The core module is mandatory, while guava is optional. There are other optional modules (this question represents a minimal testcase).

Each module exposes a set of methods that the user can invoke:

class CoreVerifier
{
  MapVerifier verify(Map);
}

class GuavaVerifier
{
  MultimapVerifier verify(Multimap);
}

What I want

  • Provide users a class that exports all the methods in a single place:

    class UnifiedVerifier
    {
      MapVerifier verify(Map);
      MultimapVerifier verify(Multimap);
    }
    
    
  • I want users to be able to use this class even if optional modules (e.g. guava) are missing at runtime. Meaning, the UnifiedVerifier is compiled with all libraries on the classpath but at runtime the guava module is not present.

  • If users attempt to invoke a method whose corresponding module is missing, I want them to get a runtime exception.

What actually happens

  • If users attempt to invoke Core methods in UnifiedVerifier from application code (with the Core module on the classpath but without the Guava module on the classpath), javac fails with:

    Application.java: cannot access MultimapVerifier
      class file for MultimapVerifier not found
    
    

Meaning, even though users do have the Core module on the classpath and they are not trying to interact with the Guava module, the compiler still refuses to accept the method invocation.

Is there a way to achieve this sort of thing in Java?





Aucun commentaire:

Enregistrer un commentaire