Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 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.                 if (Command.class.isAssignableFrom(clazz)) {
  19.                     commands.put(clazz.getSimpleName().toLowerCase(), (Command) clazz.newInstance());
  20.                 }
  21.             } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
  22.                 e.printStackTrace();
  23.             }
  24.         });
  25.     }
  26.  
  27.     public static void executeCommand(String options) {
  28.         String command = options.split(" ")[0];
  29.  
  30.         if (commands.containsKey(command)) {
  31.             Command currentCommand = commands.get(command);
  32.  
  33.             if (command.startsWith("-h")) {
  34.                 JTerm.out.println(currentCommand.getSyntax());
  35.                 return;
  36.             }      
  37.            
  38.             // Parameters of the execute() can be changed to an Array/ArrayList
  39.             currentCommand.execute(options.substring(command.length() + 1));
  40.         } else {
  41.             System.err.printf("Unkown command %s%n", command);
  42.         }
  43.     }
  44. }
  45.  
  46. abstract class Command {
  47.  
  48.     protected String syntax;
  49.  
  50.     public abstract void execute(String parameters);
  51.  
  52.     public String getSyntax() {
  53.         return syntax;
  54.     }
  55. }
  56.  
  57. class Echo extends Command {
  58.  
  59.     public Echo() {
  60.         super.syntax = "echo ...";
  61.     }
  62.  
  63.     @Override
  64.     public void execute(String parameters) {
  65.         System.out.println(parameters);
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement