Conditional Java Package Distributions
I know there isn't such a thing as conditional compilation as in C/C++ but I wonder if it is possible to produce a java program conditionally based on requirements. For example, there could be a public version which co开发者_高级运维ntains some features and private version which contains more features.
Am I right to believe that the only way to achieve this is with the help of something like plugins, i.e. the different features are found dynamically if they are present in the classpath?
I would have multiple modules for your application and multiple jars. I would have all the "private" features in a jar by itself and the rest in one or more jars.
Your application would then use the features which are available in the jars distributed (there are any number of ways to do this)
A library which you might find useful is Reflections This library allows you to find all the class which implement interface or have an annotation. So you could have a Feature
interface and ask it to give you all the class which are Feature
s
It is not unusual to separate a java package into using interfaces and implementations of those interfaces.
At package time you can filter out/in the implementations based upon conditions by using Ant or Maven. Like a different and more feature rich implementation for private versions.
Checking the classpath is ok, but a better bet is to use JNDI and let separate parts of your application find each other by registering them self into a shared JDNI context.
You can easily achieve that in a OOPS way.
Organize the features
as following
Interface Feature
Class BaseFeature
Class BasicFeature1
Class BasicFeature2
Class SpecialFeature1
Class SpecialFeature2
Class PremiumFeature1
...
Then load the features centrally by having some sort of FeaturesManager
class FeatureManager {
String[] globalFeatureClasses = new String[]{--list all of them here, or load an external list etc--};
for each feature in globalFeaturesList {
if (class.forName(feature) != null) { // class is available
// this feature available
} else {
// this feature is not available
}
}
}
The features
will implement other interfaces to provide behaviour
etc.
You can then build distribution packages containing just the basic features, basic + advanced features or premium version containing all features including premium ones. Because the application will automatically detect available features, you can ship them later as well in jars which just need to be placed on classpath along others.
Ofcourse this design needs to be developed further to be effectively used, but you get the idea.
精彩评论