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

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

    Try:

    Class klaz = Class.forName(s).asSubclass(Importable.class);
    

    Here are some snippets to illustrate the problems:

    Class klazz = String.class; // doesn't compile!
    // "Type mismatch: cannot convert from Class to Class"
    

    However:

    Class klazz = String.class; // compiles fine!
    

    So for an interface, you definitely need the upper-bounded wildcard. The asSubclass is as suggested by doublep.

    API links

    • Class asSubclass(Class clazz)
      • Casts this Class object to represent a subclass of the class represented by the specified class object. Checks that that the cast is valid, and throws a ClassCastException if it is not. If this method succeeds, it always returns a reference to this class object.

    Related questions

    • What is the difference between and ?

    See also

    • Java Tutorials/Generics/Subtyping
    • More fun with wildcards

提交回复
热议问题