0

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?

Gaurav
  • 31
  • 2

3 Answers3

2

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);
inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • There is a syntax error if I write like mControl = (Component) tbClass.newInstance(ObjContext); – Gaurav Jun 28 '11 at 18:42
  • What is the `Component` class you are referring to? I couldn't find any public `Component` class in Android, – inazaruk Jun 28 '11 at 18:46
0

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.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
0

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153