Loading a Class from a String

前端 未结 9 2298
[愿得一人]
[愿得一人] 2020-12-13 09:15

I want to instantiate a class by the value of a String. I found several tutorials that show several methods for doing this. The class MUST inherit from a certain interface

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 10:09

    What you have may work, but you don't have to load the class using the same classloader that loaded ImplementMe. This should work equally well:

    Object newInstance = this.getClass().getClassLoader().loadClass("my.package.IImplementedYou").newInstance();
    

    The important thing is that the classloader knows both the class file with the implementation of "my.package.IImplementedYou" and the class with the implementation of "ImplementMe".

    You may explicitly check that IImplementedYou really implements ImplementMe like this:

    if(newInstance instanceof my.package.IImplementedYou) {  
        ((ImplementMe)newInstance).runMe(); 
    }
    

    You may also check that IImlementedYou really is implementing the interface before creating the instance:

    Class c = this.getClass().getClassLoader().loadClass("my.package.IImplementedYou");
    if(ImplementMe.class.isAssignableFrom(c)) {
        Object newInstance = c.newInstance(); 
    }
    

提交回复
热议问题