Console input
The Console class allows the user to interact with a simple console application, using textual commands that you define.

Here's a simple example of its use:


import java.util.Arrays;
import java.io.Console;

/**
* Simple interactive console application.
* Uses the java.io.Console class of Java 6.
*/
public final class Console6 {

  public static final void main(String... aArgs){
    Console console = System.console();
    //read user name, using java.util.Formatter syntax :
    String username = console.readLine("User Name? ");

    //read the password, without echoing the output 
    char[] password = console.readPassword("Password? ");

    //verify user name and password using some mechanism (elided)

    //the javadoc for the Console class recommends "zeroing-out" the password 
    //when finished verifying it :
    Arrays.fill(password, ' ');

    console.printf("Welcome, %1$s.", username);
    console.printf(fNEW_LINE);

    String className = console.readLine("Please enter a package-qualified class name:");
    Class theClass = null;
    try {
      theClass = Class.forName(className);
      console.printf("The inheritance tree: %1$s", getInheritanceTree(theClass));
    }
    catch(ClassNotFoundException ex){
      console.printf("Cannot find that class.");
    }

    //this version just exits, without asking the user for more input
    console.printf("Bye.");
  }
  
  // PRIVATE
  private static final String fNEW_LINE = System.getProperty("line.separator");

  private static String getInheritanceTree(Class aClass){
    StringBuilder superclasses = new StringBuilder();
    superclasses.append(fNEW_LINE);
    Class theClass = aClass;
    while (theClass != null) {
      superclasses.append(theClass);
      superclasses.append(fNEW_LINE);
      theClass = theClass.getSuperclass();
    }
    superclasses.append(fNEW_LINE);
    return superclasses.toString();
  }
} 

An example run:

>java  Console6
User Name? john
Password?
Welcome, john.
Please enter a package-qualified class name:java.util.ArrayList
The inheritance tree:
class java.util.ArrayList
class java.util.AbstractList
class java.util.AbstractCollection
class java.lang.Object

Bye.

JDK < 6

The Console class was added in Java 6. The following is an extended example of using an older version of the JDK. Here, input is read from the console in a continuous loop. As well, it has separated the problem into several parts, such that some parts can be reused in other console applications.

As in the previous example, the user inputs a package-qualified class name, and the corresponding inheritance tree is displayed.

An example run:

>java -cp . Console InheritanceInterpreter
Please enter a class name>as;k
Invalid.  Example:"java.lang.String">java.lang.String
The inheritance tree:
class java.lang.String
class java.lang.Object
Please enter a class name>
Invalid.  Example:"java.lang.String">
Invalid.  Example:"java.lang.String">....
Invalid.  Example:"java.lang.String">a;lskf
Invalid.  Example:"java.lang.String">java.sql.SQLWarning
The inheritance tree:
class java.sql.SQLWarning
class java.sql.SQLException
class java.lang.Exception
class java.lang.Throwable
class java.lang.Object
Please enter a class name>java.util.GregorianCalendar
The inheritance tree:
class java.util.GregorianCalendar
class java.util.Calendar
class java.lang.Object
Please enter a class name>exit

Bye.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
* Sends text back and forth between the command line and an
* Interpreter. JDK less than 6.
*/
public final class Console {

  /**
  * Build and launch a specific <code>Interpreter</code>, whose
  * package-qualified name is passed in on the command line.
  */
  public static void main(String... aArguments) {
    try {
      Class theClass = Class.forName(aArguments[0]);
      Interpreter interpreter = (Interpreter)theClass.newInstance();
      Console console = new Console(interpreter);
      console.run();
    }
    catch (ClassNotFoundException ex){
      System.err.println(ex + " Interpreter class must be in class path.");
    }
    catch(InstantiationException ex){
      System.err.println(ex + " Interpreter class must be concrete.");
    }
    catch(IllegalAccessException ex){
      System.err.println(ex + " Interpreter class must have a no-arg constructor.");
    }
  }

  public Console(Interpreter aInterpreter) {
    if (aInterpreter == null) {
      throw new IllegalArgumentException("Cannot be null.");
    }
    fInterpreter = aInterpreter;
  }

  /**
  * Display a prompt, wait for a full line of input, and then parse
  * the input using an Interpreter.
  *
  * Exit when <code>Interpreter.parseInput</code> returns true.
  */
  public void run() {
    display(fInterpreter.getHelloPrompt());

    //pass each line of input to fInterpreter, and display
    //fInterpreter's result
    InputStreamReader inputStreamReader = new InputStreamReader(System.in);
    BufferedReader stdin = new BufferedReader(inputStreamReader);
    boolean hasRequestedQuit = false;
    String line = null;
    List<Object> result = new ArrayList<Object>();
    try {
      while(!hasRequestedQuit){
        line = stdin.readLine();
        //note that "result" is passed as an "out" parameter
        hasRequestedQuit = fInterpreter.parseInput(line, result);
        display(result);
        result.clear();
      }
    }
    catch (IOException ex) {
      System.err.println(ex);
    }
    finally {
      display(fBYE);
      shutdown(stdin);
    }
  }

  // PRIVATE
  private static final String fBYE = "Bye.";
  private Interpreter fInterpreter;

  /**
  * Display some text to stdout.
  * The result of toString() is used.
  */
  private void display(Object aText){
    System.out.print(aText.toString());
    System.out.flush();
  }

  /**
  * Display a List of objects as text in stdout, in the order returned
  * by the iterator of aText.
  */
  private void display(List<Object> aText) {
    for(Object item : aText){
      display(item);
    }
  }

  private void shutdown(Reader aStdin){
    try {
      aStdin.close();
    }
    catch (IOException ex){
      System.err.println(ex);
    }
  }
} 



import java.util.*;

/**
* Parse a line of text and return a result.
*/
public interface Interpreter {

  /**
  * @param aLine is non-null.
  * @param aResult is a non-null, empty List which acts as an "out"
  * parameter; when returned, aResult must contain a non-null, non-empty
  * List of items which all have a <code>toString</code> method, to be used
  * for displaying a result to the user.
  *
  * @return true if the user has requested to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */
  boolean parseInput(String aLine, List<Object> aResult);

  /**
  * Return the text to be displayed upon start-up of the Interpreter.
  */
  String getHelloPrompt();
} 



import java.util.*;

/**
* Given a package-qualified class name, return the names of the classes in
* the inheritance tree.
*/
public final class InheritanceInterpreter implements Interpreter {

  /**
  * @param aLine is a non-null name of a class.
  * @param aResult is a non-null, empty List which acts as an "out"
  * parameter; when returned, aResult must contain a non-null, non-empty
  * List of class names which form the inheritance tree of the input class.
  *
  * @return true if the user has requeseted to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */
  public boolean parseInput (String  aLine, final List aResult) {
    if (aResult == null) {
      throw new IllegalArgumentException("Result param cannot be null.");
    }
    if (!aResult.isEmpty()){
      throw new IllegalArgumentException("Result param must be empty.");
    }
    if (aLine == null) {
      throw new IllegalArgumentException("Line must not be null.");
    }

    boolean hasRequestedQuit = aLine.trim().equalsIgnoreCase(fQUIT) ||
                               aLine.trim().equalsIgnoreCase(fEXIT);
    if (hasRequestedQuit) {
      aResult.add(fNEW_LINE);
    }
    else {
      try {
        Class theClass = Class.forName(aLine);
        StringBuilder superclasses = new StringBuilder();
        superclasses.append(fHEADER);
        superclasses.append(fNEW_LINE);
        while (theClass != null) {
          superclasses.append(theClass);
          superclasses.append(fNEW_LINE);
          theClass = theClass.getSuperclass();
        }
        aResult.add(superclasses);
        aResult.add(fDEFAULT_PROMPT);
      }
      catch (ClassNotFoundException ex){
        //recover by asking the user for corrected input
        aResult.clear();
        aResult.add(fERROR_PROMPT);
      }
    }

    assert !aResult.isEmpty(): "Result must be non-empty.";

    return hasRequestedQuit;
  }

  /**
  * Return the text to be displayed upon start-up of the Interpreter.
  */
  public String getHelloPrompt() {
    return fHELLO_PROMPT;
  }

  // PRIVATE
  private static final String fHELLO_PROMPT = "Please enter a class name>";
  private static final String fDEFAULT_PROMPT = "Please enter a class name>";
  private static final String fERROR_PROMPT = "Invalid.  Example:\"java.lang.String\">";
  private static final String fHEADER = "The inheritance tree:";
  private static final String fQUIT = "quit";
  private static final String fEXIT = "exit";
  private static final String fNEW_LINE = System.getProperty("line.separator");
} 



See Also :
Get size of object in memory
Construct Object using class name
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -