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

后端 未结 5 1385
梦毁少年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:14

    The issue is Class.forName is a static method with the following definition

    public static Class forName(String className) throws ClassNotFoundException

    Therefore it is not a bound parameter type at all and compiler would definitely throw the cast warning here as it has no way to guarantee the string name of the class would always give you the implementation of the interface.

    If you know for sure that the string name passed into the method would be an implementation of the interface you can use SuppressWarnings annotation. But I dont think ther eis any other cleaner way to use forName with generics

提交回复
热议问题