Creating an instance using the class name and calling constructor

前端 未结 10 2568
醉话见心
醉话见心 2020-11-22 05:51

Is there a way to create an instance of a particular class given the class name (dynamic) and pass parameters to its constructor.

Something like:

Obj         


        
10条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 06:37

    Another helpful answer. How do I use getConstructor(params).newInstance(args)?

    return Class.forName(**complete classname**)
        .getConstructor(**here pass parameters passed in constructor**)
        .newInstance(**here pass arguments**);
    

    In my case, my class's constructor takes Webdriver as parameter, so used below code:

    return Class.forName("com.page.BillablePage")
        .getConstructor(WebDriver.class)
        .newInstance(this.driver);
    

提交回复
热议问题