集册 Java实例教程 构造函数获取并使用newInstance()调用

构造函数获取并使用newInstance()调用

欢马劈雪     最近更新时间:2020-01-02 10:19:05

562
构造函数获取并使用newInstance()调用

import java.io.Console;

import java.nio.charset.Charset;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;// from 时 代 J a v a - N o w J a v a . c o m

import java.lang.reflect.InvocationTargetException;

import static java.lang.System.out;


public class ConsoleCharset {

    public static void main(String... args) {

        Constructor[] ctors = Console.class.getDeclaredConstructors();

        Constructor ctor = null;

        for (int i = 0; i < ctors.length; i++) {

            ctor = ctors[i];

            if (ctor.getGenericParameterTypes().length == 0)

                break;

        }


        try {

            ctor.setAccessible(true);//来 自 nowjava.com - 时  代  Java

            Console c = (Console) ctor.newInstance();

            Field f = c.getClass().getDeclaredField("cs");

            f.setAccessible(true);

            out.format("Console charset         :  %s%n", f.get(c));

            out.format("Charset.defaultCharset():  %s%n",

                    Charset.defaultCharset());


            // production code should handle these exceptions more gracefully

        } catch (InstantiationException x) {

            x.printStackTrace();

        } catch (InvocationTargetException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        } catch (NoSuchFieldException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文