Class and static method Class.forName() drive me crazy

后端 未结 5 1372
梦毁少年i
梦毁少年i 2020-12-30 08:51

this code doesn\'t compile. I\'m wondering what I am doing wrong:

private static Importable getRightInstance(String s) throws Exception {
 Class

        
5条回答
  •  执念已碎
    2020-12-30 09:15

    where Importable is an interface and the string s is the name of an implementing class.

    The compiler can't know that, hence the error.

    Use a cast. It is easier to cast the constructed object (because that is a checked cast), than the class object itself.

    Class c = Class.forName(s);
    Importable i = (Importable) c.newInstance();
    return i;
    

提交回复
热议问题