jeudi 16 juillet 2015

How to access a constructor of with default access (or package-default)

I'm trying to instantiate the constructor of a class which I imported as a Maven dependency via it's coordinates. The problem I have is that the particular constructor of this class, is invisible to me because it has no access modifier associated with it so it is default, meaning I can't access it from outside.

I know there is a way to access private methods via reflections, using getDeclaredMethod() method of class Method, but this doesn't work for constructors (please correct me if I'm wrong).

The class I'm trying to use is here:

public class DecisionTableBuilder {

   // Notice no access modifier here so it's package-default
   DecisionTableBuilder(Log log, File in, File out) {
      some stuff ...
   }

   // public constructor
   public DecisionTableBuilder() {}

   // Method 1
   public void compiler(File schema) {
      some stuff ...
   }

   // Method 2
   public void linker(File attribute) {
      some stuff ...
   }
}

Here is my toplevel in a separate project:

public class TopLevel {

   public void testDecisionTableBuilder() {

      // I get an error saying the constructor DecisionTableBuilder is not visible
      DecisionTableBuilder builder = new DecisionTableBuilder();

      // This works just fine, but no constructor...
      DecisionTableBuilder builder2;

      // This doesn't really work
      Method[] m = DecisionTableBuilder.class.getDeclaredMethods("DecisionTableBuilder", "Log", "File", "File");

   }
}

How can I access the Constructor and methods in a toplevel class which I created in a new project? Any assistance would be much appreciated





Aucun commentaire:

Enregistrer un commentaire