当前位置: 动力学知识库 > 问答 > 编程问答 >

How to create TextView with reflection on android?

问题描述:

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

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: