Loading a Class from a String

前端 未结 9 2280
[愿得一人]
[愿得一人] 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 09:53

    Here's how I would do it:

    ImplementMe noCastNeeded = 
        this.getClassLoader()
            .loadClass("my.package.IImplementedYou")
            .asSubclass(ImplementMe.class).newInstance();
    

    There are some Exceptions to catch but that's ok I think. :)

提交回复
热议问题