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?

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

There is a syntax error if I write like mControl = (Component) tbClass.newInstance(ObjContext);
What is the Component class you are referring to? I couldn't find any public Component class in Android,
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.