集册 Java实例教程 调用构造函数并使用反射提供参数值

调用构造函数并使用反射提供参数值

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

579
调用构造函数并使用反射提供参数值

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.util.HashMap;
/* from 
N o w J a v a . c o m*/

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");

        for (String k : aliases)

            out.format("  %s%n", k);//from 时 代 J a v a 公 众 号 - N o w J a v  a . c o m

    }

}


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();

        }

    }

}


展开阅读全文