jeudi 30 juin 2022

Instantiate different versions of same class with changed constructor and "abstract" modifier

I am writing a Java program which uses external libraries. I want to write my code so it is compatible with two different versions of one specific library.

The problem is, they changed a class (called Configuration in my example) to abstract, added an abstract method and changed the constructor from a no-argument to parameterized constructor. I am not able to influence the external library and I have to work with what I got.

Old class example

public class Configuration {

    public Configuration() {
        //Some code...
    }

    public static void main(String[] args) {
        Configuration conf = new Configuration();
        //Some code...
    }

}

New class example

public abstract class Configuration {

    public Configuration(boolean isCool, Map<String, String> entries, Object otherThing) {
        //Some code...
    }

    public abstract int doSomething();
    
    public static void main(String[] args) {
        Configuration conf = new MyConfiguration(false, null, new Object());
        //Some code...
    }

}

My implementation

public class MyConfiguration extends Configuration {
    
    public MyConfiguration(boolean isCool, Map<String, String> entries, Object otherThing) {
        super(isCool, entries, otherThing);
    }
    
    public MyConfiguration() {
        //needs super constructor call!?
    }

    public int doSomething() {
        //Some code...
        return -1;
    }

    public static void main(String[] args) {
        int version = 0;
        Configuration conf = version > 2 ? new MyConfiguration(false, null, new Object()) : new MyConfiguration();  
        //Some code...
    }

}

IDE error

The no-argument constructor of my custom class MyConfiguration needs to call the constructor of the superclass in order to be compiled. However, the old class does not have a parameterized constructor, so I will run into an error if I do that.

  • Are there any tricks how I don't have to call the super constructor?
  • Maybe there is a way using reflection to do what I want?




Aucun commentaire:

Enregistrer un commentaire