集册 Java实例教程 使用反射按参数类型调用构造方法

使用反射按参数类型调用构造方法

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

484
使用反射按参数类型调用构造方法
/** 时 代 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 ConstructorTroubleAgain {

    public ConstructorTroubleAgain() {

    }


    public ConstructorTroubleAgain(Integer i) {

    }


    public ConstructorTroubleAgain(Object o) {

        out.format("Constructor passed Object%n");

    }


    public ConstructorTroubleAgain(String s) {

        out.format("Constructor passed String%n");

    }//时 代 J a v a 公 众 号 - nowjava.com 提供


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

        String argType = (args.length == 0 ? "" : args[0]);

        try {

            Class<?> c = Class.forName("ConstructorTroubleAgain");

            if ("".equals(argType)) {

                // IllegalArgumentException: wrong number of arguments

                Object o = c.getConstructor().newInstance("foo");

            } else if ("int".equals(argType)) {

                // NoSuchMethodException - looking for int, have Integer

                Object o = c.getConstructor(int.class);

            } else if ("Object".equals(argType)) {

                // newInstance() does not perform method resolution

                Object o = c.getConstructor(Object.class)

                        .newInstance("foo");

            } else {

                assert false;

            }


            // production code should handle these exceptions more gracefully

        } catch (ClassNotFoundException x) {

            x.printStackTrace();

        } catch (NoSuchMethodException x) {

            x.printStackTrace();

        } catch (InvocationTargetException x) {

            x.printStackTrace();

        } catch (InstantiationException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文