KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > console > ReflectCommandFactory


1 package org.sapia.console;
2
3 import java.util.*;
4
5
6 /**
7  * A command factory that creates <code>Command</code> instances
8  * dynamically, by resolving the command name to a class. The command's
9  * name has its first letter capitalized, and it is prepended with successive
10  * package names; the first command class that is found for a given package has
11  * an object instantiated from it.
12  * <p>
13  * If all packages have been visited and no command class was found
14  * for the given command name, then a <code>CommandNotFoundException</code>
15  * is thrown.
16  *
17  * @see #getCommandFor(String)
18  * @author Yanick Duchesne
19  * 29-Nov-02
20  */

21 public class ReflectCommandFactory implements CommandFactory {
22   private List _pckgs = new ArrayList();
23
24   /**
25    * @see org.sapia.console.CommandFactory#getCommandFor(String)
26    */

27   public Command getCommandFor(String JavaDoc name) throws CommandNotFoundException {
28     Command cmd = null;
29
30     for (int i = 0; i < _pckgs.size(); i++) {
31       try {
32         cmd = (Command) Class.forName((String JavaDoc) _pckgs.get(i) + "." +
33             firstToUpper(name)).newInstance();
34       } catch (ClassNotFoundException JavaDoc e) {
35         // noop
36
} catch (Throwable JavaDoc t) {
37         throw new CommandNotFoundException(t + ": " + t.getMessage());
38       }
39     }
40
41     if (cmd == null) {
42       throw new CommandNotFoundException(name);
43     }
44
45     return cmd;
46   }
47
48   /**
49    * Adds a package to this instance.
50    */

51   public ReflectCommandFactory addPackage(String JavaDoc name) {
52     _pckgs.add(name);
53
54     return this;
55   }
56
57   private String JavaDoc firstToUpper(String JavaDoc name) {
58     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
59
60     for (int i = 0; i < name.length(); i++) {
61       if (i == 0) {
62         buf.append(Character.toUpperCase(name.charAt(i)));
63       } else {
64         buf.append(name.charAt(i));
65       }
66     }
67
68     return buf.toString();
69   }
70 }
71
Popular Tags