Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. public class JTerm {
  2.  
  3.     private static HashMap<String, Command> commands = new HashMap<>();
  4.  
  5.     public static void main(String[] args) {
  6.         // init
  7.         init("jterm.command");
  8.        
  9.         // execute
  10.         executeCommand("echo hello world");
  11.     }
  12.  
  13.     public static void init(String packageName) {
  14.         URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
  15.         Arrays.stream(new File(root.getFile()).listFiles()).forEach(file -> {
  16.             try {
  17.                 Class clazz = Class.forName(String.format("%s.%s", packageName, file.getName().replaceAll(".class$", "")));
  18.                 commands.put(clazz.getSimpleName().toLowerCase(), (Command) clazz.newInstance());
  19.             } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
  20.                 e.printStackTrace();
  21.             }
  22.         });
  23.     }
  24.  
  25.     public static void executeCommand(String options) {
  26.         String command = options.split(" ")[0];
  27.  
  28.         if (commands.containsKey(command)) {
  29.             Command currentCommand = commands.get(command);
  30.  
  31.             if (command.startsWith("-h")) {
  32.                 JTerm.out.println(currentCommand.getSyntax());
  33.                 return;
  34.             }      
  35.            
  36.             // Parameters of the execute() can be changed to an Array/ArrayList
  37.             currentCommand.execute(options.substring(command.length() + 1));
  38.         } else {
  39.             System.err.printf("Unkown command %s%n", command);
  40.         }
  41.     }
  42. }
  43.  
  44. abstract class Command {
  45.  
  46.     protected String syntax;
  47.  
  48.     public abstract void execute(String parameters);
  49.  
  50.     public String getSyntax() {
  51.         return syntax;
  52.     }
  53. }
  54.  
  55. class EchoCommand extends Command {
  56.  
  57.     public EchoCommand() {
  58.         super.syntax = "echo ...";
  59.     }
  60.  
  61.     @Override
  62.     public void execute(String parameters) {
  63.         System.out.println(parameters);
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement