can I reflectively instantiate a generic type in java?

后端 未结 4 930
有刺的猬
有刺的猬 2020-12-01 11:34

Is it possible to reflectively instantiate a generic type in Java? Using the technique described here I get an error because class tokens cannot be generic. Take the example

4条回答
  •  无人及你
    2020-12-01 11:49

    You don't need that line. Nor do you need the constructor as you're just using the default one. Just instantiate the class directly:

    public static void main(String[] args) throws Exception {
            Class someClass = Class.forName(args[0]);
            Creator creator = (Creator) someClass.newInstance();
    }
    

    If you insist, you'll only be able to get halfway there:

    public static void main(String[] args) throws Exception {
        Class someClass = Class.forName(args[0]);
        Class creatorClass = someClass.asSubclass(Creator.class);
        Constructor creatorCtor = creatorClass.getConstructor((Class[]) null);
        Creator creator = (Creator) creatorCtor.newInstance((Object[]) null);
    }
    

提交回复
热议问题