Loading a Class from a String

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

    You can shorten it a bit like

    ImplementMe a = (ImplementMe) Class
                                   .forName("my.package.IImplementedYou")
                                   .newInstance();
    

    but you can't get rid of the cast. There may be a way to avoid the cast, but only if you can avoid the subproblem of loading class by name.

提交回复
热议问题