Am I implementing a generics-based Java factory correctly?

后端 未结 3 1404
青春惊慌失措
青春惊慌失措 2021-02-05 14:40

I don\'t believe I am implementing the factory pattern correctly because the Application class\' createDocument method accepts any class type, not just

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 15:07

    You should bound your generic so that it is only using T's that inherit Document. example:

    public class Application {
        //Add extends Document after T
        public static  T createDocument(Class documentClass) throws InstantiationException, IllegalAccessException {
            return documentClass.newInstance();
        };
    }
    

提交回复
热议问题