Java examples for Language Basics:Console
A static method which peeks into the java.io.Console class and manually turns on or off echoing in the given console.
/*/*from w w w . j av a2s .c om*/ * Copyright (c) 2013 Jean Niklas L'orange. All rights reserved. * * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file LICENSE at the root of this distribution. * * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * * You must not remove this notice, or any other, from this software. */ //package com.java2s; import java.io.Console; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { public static void main(String[] argv) throws Exception { boolean on = true; System.out.println(setEcho(on)); } /** * A static method which peeks into the {@link java.io.Console} class and * manually turns on or off echoing in the given console. * * @param on whether to set echoing on or off. * * @exception NoSuchMethodException if Java's own console class have no * private method named "echo". * @exception NoSuchFieldException if Java's own console class have no * private field named "echoOff". * @exception InvocationTargetException if Java's own console class have a * private method named "echo", but that this method tries to invoke that * method erroneously. * @exception IllegalAccessException if the access restrictions prohibits * this method from modifying and using private methods in Java's own * console class. */ public static synchronized boolean setEcho(boolean on) throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException, InvocationTargetException { Class params[] = new Class[1]; params[0] = Boolean.TYPE; Method echo = Console.class.getDeclaredMethod("echo", params); echo.setAccessible(true); boolean res = (Boolean) echo.invoke(null, on); Field echoOff = Console.class.getDeclaredField("echoOff"); echoOff.setAccessible(true); echoOff.set(null, res); return res; } }