summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/beust/jcommander/internal/JDK6Console.java
blob: 70cb186b6a00a2e98d4e3221f786f8029c259e44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.beust.jcommander.internal;

import com.beust.jcommander.ParameterException;

import java.io.PrintWriter;
import java.lang.reflect.Method;

public class JDK6Console implements Console {

  private Object console;

  private PrintWriter writer;

  public JDK6Console(Object console) throws Exception {
    this.console = console;
    Method writerMethod = console.getClass().getDeclaredMethod("writer", new Class<?>[0]);
    writer = (PrintWriter) writerMethod.invoke(console, new Object[0]);
  }

  public void print(String msg) {
    writer.print(msg);
  }

  public void println(String msg) {
    writer.println(msg);
  }

  public char[] readPassword(boolean echoInput) {
    try {
      writer.flush();
      Method method;
      if (echoInput) {
          method = console.getClass().getDeclaredMethod("readLine", new Class<?>[0]);
          return ((String) method.invoke(console, new Object[0])).toCharArray();
      } else {
          method = console.getClass().getDeclaredMethod("readPassword", new Class<?>[0]);
          return (char[]) method.invoke(console, new Object[0]);
      }
    }
    catch (Exception e) {
      throw new ParameterException(e);
    }
  }

}