Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA \ Compile a function only on runtime

My code is used as part of two big versions and interact with external interface. In one of the versions new API was added (I need to call a new method).

I would like to prevent maintaining two versions of my code, and use if statement:

If VersionX
   Do Method1()
If VersionY
   Do Method2()

assuming method2() is the new function I need to call, is there a way that the code can compile only on runtime (means that if I run on VersionX system, there would be no problem of compilation and exceptions though method 2() does not exist there)?

like image 997
Eyal Avatar asked Dec 28 '25 21:12

Eyal


1 Answers

You can achieve this with an interface and two classes:

interface API {
    void Method();
}

class APIX implements API {
    void Method() {
        someInstance.Method1();
    }
}

class APIY implements API {
    void Method() {
        anotherInstance.Method2();
    }
}

Then depending on the current version, you create an instance of either APIX or APIY:

API api;
if (isVersionX) 
    api = new APIX();
else
    api = new APIY();
api.Method();

This code is compiled against the newer API wich contains both methods. Since class loading is on demand only, the class using the newer method is not loaded when only the old API is available and you don't have any conflicts at run-time.

like image 185
Codo Avatar answered Dec 30 '25 13:12

Codo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!