Creating an instance using the class name and calling constructor

前端 未结 10 2566
醉话见心
醉话见心 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:45

    If class has only one empty constructor (like Activity or Fragment etc, android classes):

    Class myClass = Class.forName("com.example.MyClass");    
    Constructor constructor = myClass.getConstructors()[0];
    

提交回复
热议问题