Last active
May 7, 2023 12:55
-
-
Save msimonin/6438085 to your computer and use it in GitHub Desktop.
[java] plugin management by reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// replace schedulerSettings ... | |
try{ | |
String pluginsDirectory = schedulerSettings.getPluginsDirectory(); | |
Class placementClass = PluginsUtils.getClassFromDirectory(pluginsDirectory , placementPolicy); | |
log_.debug(String.format("instantiate the placement policy %s from the jar",placementPolicy)); | |
Object placementObject = placementClass.getConstructor(ResourceDemandEstimator.class).newInstance(estimator); | |
placement = (PlacementPolicy)placementObject; | |
} | |
catch (Exception e) | |
{ | |
e.printStackTrace(); | |
log_.debug("Back to default placement policy" ) ; | |
placement = new FirstFit(estimator); | |
} | |
} | |
/** | |
* Gets class from directory | |
*/ | |
public static Class getClassFromDirectory(String pluginsDirectory, String classToLoad) | |
throws MalformedURLException, ClassNotFoundException | |
{ | |
log_.debug("Try to look into the plugins directory " + pluginsDirectory); | |
File dir = new File(pluginsDirectory); | |
File[] files = dir.listFiles(new FilenameFilter(){ | |
@Override | |
public boolean accept(File dir, String name) { | |
return name.endsWith(".jar"); | |
} | |
}); | |
URL[] urls = new URL[files.length]; | |
int i = 0 ; | |
for (File file:files) | |
{ | |
log_.debug("file " + file.toURI().toURL().toString()); | |
urls[i] = file.toURI().toURL(); | |
i++; | |
} | |
log_.debug("number of plugins found " + urls.length ); | |
ClassLoader loader = new URLClassLoader(urls); | |
Class classLoaded = loader.loadClass(String.valueOf(classToLoad)); | |
return classLoaded; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment