1. 程式人生 > >java反射(一):反射的演變

java反射(一):反射的演變

有三種方式:

1.通過object物件的例項呼叫getClass

        String hello = "hello world";
        Class<?> helloClass = hello.getClass();
        System.out.println(helloClass);

2.通過包名.類名.class

        Class<?> hello1Class = java.lang.String.class;
        System.out.println(hello1Class);

3.通過Class的forName方法

        Class<?> hello2Class = Class.forName("java.lang.String");
        System.out.println(hello2Class);

通過class可以進行物件例項化

1.通過newInstance()

        Class<?> bookClass = Class.forName("com.mingji.Book");
        Book book = (Book)bookClass.newInstance();

2.通過工廠模式:

class MyFactory {
    public static Message getInstance(String str) {
        if ("news".equalsIgnoreCase(str)) {
            return new News();
        } else if ("emails".equalsIgnoreCase(str)) {
            return new Emails();
        } else  {
            return null;
        }
    }
}

        Message message = MyFactory.getInstance("news");
        message.print("今天要下雨");

3.通過去掉工廠模式的固化問題

class MyFactory2 {
    public static Message getInstance(String str) {
        try {
            return (Message)Class.forName(str).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

        Message message1 = MyFactory2.getInstance("com.mingji.News");
        message1.print("今天要下雨");

4.通過key-value來去掉程式對類名的耦合,我們通過屬性檔案來解決

        Properties pro = new Properties();
        pro.load(new FileInputStream("info.properties"));
        Message message2 = MyFactory2.getInstance(pro.getProperty("message.className"));
        message2.print("今天要下雨");