Search code examples
javareflectionconstructorillegalaccessexception

Access package accessible constructor outside package


I knot that it sound a bit controversial, but I must access a constructor that is protected with the package accessor... however I'm outside that package, and so I was using reflection to access that constructor like so:

Constructor<TargetClass> constructor = TargetClass.class.getDeclaredConstructor(SomeClass.class);
var manager = constructor.newInstance(new SomeClass());

However when I run this, I get:

java.lang.IllegalAccessException: class com.mypackage.Application cannot access a member of class com.someotherpackage.TargetClass with modifiers ""

Are there ways to avoid this, or either other ways to access that constructor?


Solution

  • You need setAccessible.

    Constructor<TargetClass> constructor =
        TargetClass.class.getDeclaredConstructor(SomeClass.class);
    constructor.setAccessible(true);
    var manager = constructor.newInstance(new SomeClass());
    

    Reflection is almost always being a bad idea. setAccessible is worse. Modules may add further complications.