从控制台读取密码,而不回显字符。
/*- * Copyright (C) 2014 Erik Larsson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** nowjava - 时 代 Java 提供 **/ //package com.nowjava; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { /** * Read password from console without echoing characters. * * @return <code>null</code> if there is no console or end of stream is * reached when attempting to read password. */ public static char[] readPassword() { try { final Method systemConsoleMethod = java.lang.System.class .getMethod("console"); final Object consoleObject = systemConsoleMethod.invoke(null); if (consoleObject == null) { /* No console. */ return null; } final Class<? extends Object> consoleClass = Class .forName("java.io.Console"); /** from * nowjava - 时代Java **/ final Method consoleReadPasswordMethod = consoleClass .getMethod("readPassword"); final Object passwordObject = consoleReadPasswordMethod .invoke(consoleObject); if (passwordObject != null && !(passwordObject instanceof char[])) { throw new RuntimeException("Unexpected type returned from " + "java.io.Console.readPassword(): " + passwordObject.getClass().getName()); } return (char[]) passwordObject; } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } catch (NoSuchMethodException ex) { throw