Reputation: 15744
I'm trying to create a textview with reflection on android but I could not success and got an exception which I shown below. Can anyone share an example with me?
the thing what I am trying to do is very simple, I will create a textview and put some text into it with calling it's setText method.
TextView x = new TextView(this);
x.setText("asjdhjasd");
the codes
Class cls = Class.forName("android.widget.TextView");
Class param[] = new Class[1];
param[0] = context.getClass();
Constructor ct = cls.getConstructor(param); //THROWS AN EXCEPTION HERE CALLED NO SUCH METHOD EXCEPTION.
Object paramVal[] = new Object[1];
paramVal[0] = context;
Object retobj = ct.newInstance(paramVal);
I solved the problem with doing this
param[0] = Context.class; //instead of param[0] = context.getClass();
Upvotes: 0
Views: 1163
Reputation: 2322
Try this instead:
Constructor ct = cls.getConstructor( context.getClass() );
EDIT: Sorry I should have explained why.
When you see a method like this
getConstructor(Class... parameterTypes)
It isn't asking for an array of classes, it wants the classes as parameters. It's called varargs and you can read about it at http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
Upvotes: 1