JAVA \ Compile function only at runtime

My code is used as part of two large versions and interacts with an external interface. In one version, a new API was added (I need to call a new method).

I would like to prevent the saving of two versions of my code and use the if statement:

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

Assuming that method2()this is a new function that I need to call, is there a way that code can only compile at run time (does that mean that if I started the system VersionX, there would be no problems with compilation and exceptions, although method 2()it does not exist there)?

+3
source share
2 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();
    }
}

APIX APIY:

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

API, . , , , , API, .

+4

, , .

// calls a method if it exists or throws an exception.
Method method = object.getClass().getMethod("DoMethod1");
method.invoke(object);
0

All Articles