0

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?

Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
  • @user15793316 sometimes, for some reason, I forgot that the documentation exists, and people like you should just throw a rock into my head ahahah thank you so much, please consider making an answer, so that i can mark it as correct, and giving you a thumbs up – Alberto Sinigaglia May 14 '21 at 22:27

1 Answers1

1

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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305