[java] Extracting methods to make code more readable
@@ -63,11 +63,40 @@ public static void main(String[] args) {
void go() {
// It's not private to make it visible for tests
if (args.length == 0) {
- new Help(loadCommands(Main.class.getClassLoader())).configure(out, err).run();
+ showHelp(Main.class.getClassLoader());
} else {
if ("--ext".equals(args[0])) {
if (args.length > 1) {
- StringTokenizer tokenizer = new StringTokenizer(args[1], File.pathSeparator);
+ URLClassLoader loader = createExtendedClassLoader(args[1]);
+
+ // Ensure that we use our freshly minted classloader by default.
+ Thread.currentThread().setContextClassLoader(loader);
+
+ if (args.length > 2) {
+ String[] remainingArgs = new String[args.length - 2];
+ System.arraycopy(args, 2, remainingArgs, 0, args.length - 2);
+ launch(remainingArgs, loader);
+ } else {
+ showHelp(loader);
+ }
+ } else {
+ showHelp(Main.class.getClassLoader());
+ }
+
+ } else {
+ launch(args, Main.class.getClassLoader());
+ }
+ }
+ }
+
+ private static Set<CliCommand> loadCommands(ClassLoader loader) {
+ Set<CliCommand> commands = new TreeSet<>(comparing(CliCommand::getName));
+ ServiceLoader.load(CliCommand.class, loader).forEach(commands::add);
+ return commands;
+ }
+
+ private static URLClassLoader createExtendedClassLoader(String ext) {
+ StringTokenizer tokenizer = new StringTokenizer(ext, File.pathSeparator);
List<File> jars = new ArrayList<>();
while (tokenizer.hasMoreTokens()) {
File file = new File(tokenizer.nextToken());
@@ -95,34 +124,13 @@ void go() {
}
}).toArray(URL[]::new);
- URLClassLoader loader = AccessController.doPrivileged(
+ return AccessController.doPrivileged(
(PrivilegedAction<URLClassLoader>) () ->
new URLClassLoader(jarUrls, Main.class.getClassLoader()));
-
- // Ensure that we use our freshly minted classloader by default.
- Thread.currentThread().setContextClassLoader(loader);
-
- if (args.length > 2) {
- String[] remainingArgs = new String[args.length - 2];
- System.arraycopy(args, 2, remainingArgs, 0, args.length - 2);
- launch(remainingArgs, loader);
- } else {
- new Help(loadCommands(loader)).configure(out, err).run();
- }
- } else {
- new Help(loadCommands(Main.class.getClassLoader())).configure(out, err).run();
- }
-
- } else {
- launch(args, Main.class.getClassLoader());
- }
- }
}
- private static Set<CliCommand> loadCommands(ClassLoader loader) {
- Set<CliCommand> commands = new TreeSet<>(comparing(CliCommand::getName));
- ServiceLoader.load(CliCommand.class, loader).forEach(commands::add);
- return commands;
+ private void showHelp(ClassLoader loader) {
+ new Help(loadCommands(loader)).configure(out, err).run();
}
private void launch(String[] args, ClassLoader loader) {
