集册 Java实例教程 使用反射通过HashMap类型获取构造方法

使用反射通过HashMap类型获取构造方法

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

472
使用反射通过HashMap类型获取构造方法

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;/** 来自 时 代 J     a    v  a - nowjava.com**/

import java.lang.reflect.InvocationTargetException;

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

import static java.lang.System.out;


class EmailAliases {

    private Set<String> aliases;


    private EmailAliases(HashMap<String, String> h) {

        aliases = h.keySet();

    }


    public void printKeys() {

        out.format("Mail keys:%n");// from NowJava.com

        for (String k : aliases)

            out.format("  %s%n", k);

    }

}


public class RestoreAliases {


    private static Map<String, String> defaultAliases = new HashMap<String, String>();

    static {

        defaultAliases.put("Duke", "duke@i-love-java");

        defaultAliases.put("Fang", "fang@evil-jealous-twin");

    }


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

        try {

            Constructor ctor = EmailAliases.class

                    .getDeclaredConstructor(HashMap.class);

            ctor.setAccessible(true);

            EmailAliases email = (EmailAliases) ctor

                    .newInstance(defaultAliases);

            email.printKeys();


            // production code should handle these exceptions more gracefully

        } catch (InstantiationException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        } catch (InvocationTargetException x) {

            x.printStackTrace();

        } catch (NoSuchMethodException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文