简体   繁体   中英

How to call private constructor of super class from child class constructor?

In Java, I'm trying to override a class coming from a library. One of the constructors of the class is private and thus I'm not able to call it from my class. Is there a way to work around this (reflection?)?

public class LibraryClass extends ProtectedLibraryClass {
  public LibraryClass() {
    super();
  }

  private LibraryClass(Boolean useFeature) {
    super(useFeature);
  }

  // Other methods
}

public class MyClass extends LibraryClass {
  
  public MyClass() {
    super();
  }

  private MyClass(Boolean useFeature) {
    super(useFeature); // <-- This line throws exception as super class constructor is private
  }
  // Override other methods
}

I can't just call super() and then set useFeature flag as useFeature flag is final in protectedLibraryClass and is set only through it's constructor.

they made it for a reason but you can use reflection in java to create object from this class even if it private

here is example :

   public static void main(String[] args) {
        LibraryClass copy = null;
        try {
            Constructor[] constructors = LibraryClass.class.getDeclaredConstructors();
            for (Constructor constructor : constructors) {
                constructor.setAccessible(true);
                copy = (LibraryClass) constructor.newInstance();
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

I don't think this is possible, looking at this post and these docs . What you could possibly do is place the two (or however many) class files into their own package and then use the protected access modifier so that the constructor is only usable within the package. If you only place classes that inherit from the LibraryClass class it would have the same effect as making the constructor private as indicated above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM