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


i'm trying instantiate constructor of class imported maven dependency via it's coordinates. problem have particular constructor of class, invisible me because has no access modifier associated default, meaning can't access outside.

i know there way access private methods via reflections, using getdeclaredmethod() method of class method, doesn't work constructors (please correct me if i'm wrong).

the class i'm trying use here:

public class decisiontablebuilder {     // notice no access modifier here it's package-default    decisiontablebuilder(log log, file in, file out) {       stuff ...    }     // public constructor    public decisiontablebuilder() {}     // method 1    public void compiler(file schema) {       stuff ...    }     // method 2    public void linker(file attribute) {       stuff ...    } } 

here toplevel in separate project:

public class toplevel {     public void testdecisiontablebuilder() {        // error saying constructor decisiontablebuilder not visible       decisiontablebuilder builder = new decisiontablebuilder();        // works fine, no constructor...       decisiontablebuilder builder2;        // doesn't work       method[] m = decisiontablebuilder.class.getdeclaredmethods("decisiontablebuilder", "log", "file", "file");     } } 

how can access constructor , methods in toplevel class created in new project? assistance appreciated

edit

public file graphdir; public file outputdir; public log log;  constructor<decisiontablebuilder> constructor = decisiontablebuilder.class.getdeclaredconstructor(log.class,file.class,file.class); constructor.setaccessible(true); decisiontablebuilder builder =constructor.newinstance(log, graphdir, outputdir); 

would correct?

you cannot access constructors getdeclaredmethod or getdeclaredmethods. java reflection mechanism distinguishes between methods , constructors, , has separate methods accessing them.

try getdeclaredconstructors method,

constructor[] c = decisiontablebuilder.class.getdeclaredconstructors(); 

or specific constructor, getdeclaredconstructor. pass in class objects representing parameter types, not string names of classes.

constructor<decisiontablebuilder> constructor =     decisiontablebuilder.class.getdeclaredconstructor(log.class, file.class, file.class); 

you want set accessible , call newinstance create decisiontablebuilder.'

constructor.setaccessible(true); decisiontablebuilder dtb = constructor.newinstance(yourlog, infile, outfile); 

you'll of course need catch several exceptions these reflection calls can throw.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -