Search code examples
androidclassdynamicinstantiationexception

Android Dynamic Class creation gives java.lang.InstantiationException


When I am trying to create a dynamic instance of Android UI Component, it gives me "java.lang.InstantiationException".

Sample Code:

Class components[] = {TextView.class, Button.class,...}
Component mControl = null;
...
...
mControl = (Component) components[nIndexOfControl].newInstance();

Can some one guide me, what is the best way to achieve the above as I want to save if..else for each widget?


Solution

  • The TextView class does not have default constructor. Three availabale constructors are:

    TextView(Context context)
    TextView(Context context, AttributeSet attrs)
    TextView(Context context, AttributeSet attrs, int defStyle)
    

    Same thing for Button class:

    public Button (Context context)
    public Button (Context context, AttributeSet attrs)
    public Button (Context context, AttributeSet attrs, int defStyle) 
    

    You need to pass at least Context variable to instantiate all UI (descendants of View) controls.


    Change your code next way:

    Context ctx = ...;
    Class<?> components[] = {TextView.class, Button.class };
    Constructor<?> ctor = components[nIndexOfControl].getConstructor(Context.class);
    Object obj = ctor.newInstance(ctx);