Gaurav
Gaurav

Reputation: 31

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?

Upvotes: 0

Views: 1430

Answers (3)

inazaruk
inazaruk

Reputation: 74780

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);

Upvotes: 2

Karl Knechtel
Karl Knechtel

Reputation: 61515

I searched with Google for 'java class.newInstance' and:

a) I found the documentation for the java.lang.Class class, which explains the exact circumstances under which this exception is thrown:

InstantiationException - if this Class represents an abstract class, an
interface, an array class, a primitive type, or void; or if the class has
no nullary constructor; or if the instantiation fails for some other reason.

b) A suggested search term was "java class.newinstance with parameters", which finds several approaches for dealing with the "class has no nullary constructor" case, including some results from StackOverflow.

You don't have array classes, primitive types or 'void' in your list of classes, and "some other reason" is unlikely (and would be explained in the exception message anyway). If the class is abstract or an interface, then you simply can't instantiate it in any way.

Upvotes: 0

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

There is not default constructor for View objects. Take a look at the javadoc for Class.newInstance(). It throws an InstantiationException if no matching constructor is found.

Upvotes: 0

Related Questions