Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class JTerm {
- private static HashMap<String, Command> commands = new HashMap<>();
- public static void main(String[] args) {
- // init
- init("jterm.command");
- // execute
- executeCommand("echo hello world");
- }
- public static void init(String packageName) {
- URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
- Arrays.stream(new File(root.getFile()).listFiles()).forEach(file -> {
- try {
- Class clazz = Class.forName(String.format("%s.%s", packageName, file.getName().replaceAll(".class$", "")));
- if (Command.class.isAssignableFrom(clazz)) {
- commands.put(clazz.getSimpleName().toLowerCase(), (Command) clazz.newInstance());
- }
- } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
- e.printStackTrace();
- }
- });
- }
- public static void executeCommand(String options) {
- String command = options.split(" ")[0];
- if (commands.containsKey(command)) {
- Command currentCommand = commands.get(command);
- if (command.startsWith("-h")) {
- JTerm.out.println(currentCommand.getSyntax());
- return;
- }
- // Parameters of the execute() can be changed to an Array/ArrayList
- currentCommand.execute(options.substring(command.length() + 1));
- } else {
- System.err.printf("Unkown command %s%n", command);
- }
- }
- }
- abstract class Command {
- protected String syntax;
- public abstract void execute(String parameters);
- public String getSyntax() {
- return syntax;
- }
- }
- class Echo extends Command {
- public Echo() {
- super.syntax = "echo ...";
- }
- @Override
- public void execute(String parameters) {
- System.out.println(parameters);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement