Search code examples
javaclassinterfacelocale

conditional interface implementation


I want to ask if there is a possible way to conditionally implement interfaces or if there can be a workaround to what I want to do. I want to make two interfaces LangA and LangB that will only hold a very large number of final variables that are Strings used to print messages. As you probably imagine LangA is one language and LangB another one. What I want is have my message-handling class conditionally implement the interface needed based on the system's locale. I have no idea if this is possible at all in any way even with some custom ibrary, so if not, explain me if it can be worked around at least. (Quick question: is this possible in Scala? thanks!)
I have thought of a possible, but maybe not a very resource-efficient workaraound, which will have the class's constructor check the locale and set its own finals based on the values of some methodless class that will only feature the finals for each language (e.g. constructor learns that locale is locA so it sets finals myF1=LangA.myF1; myF2=LangB.myF2; etc.) Thanks in advance!


Solution

  • No, this is not possible.

    The "class X implements interface Y" relationship is fixed at compile time, and cannot be altered at runtime.

    However, using interfaces to import constants into a class is a solution that dates back to Java 1.0. This anti-pattern should not be used for new development.

    Moreover, localization with compile-time constants is not a native solution in Java. You should localize using resource bundles.

    If you need a way to switch implementations at runtime, replace constants with methods in your interface, and provide implementations that return different constants:

     interface Constants {
         double getAccelerationDueToGravity();
     }
    
     class EarthConstants implements Constants {
         double getAccelerationDueToGravity() {
             return 9.8;
         }
     }
    
     class MarsConstants implements Constants {
         double getAccelerationDueToGravity() {
             return 3.71;
         }
     }