如何在android上创建带有反射的TextView?
我正在尝试在 android 上创建一个带有反射的文本视图,但我无法成功并得到一个异常,如下所示。谁能与我分享一个例子吗?
我想做的事情非常简单,我将创建一个文本视图并通过调用它的 setText 方法将一些文本放入其中。
TextView x = new TextView(this);
x.setText("asjdhjasd");
代码
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);
我这样做解决了问题
param[0] = Context.class; //instead of param[0] = context.getClass();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

试试这个:
编辑:抱歉,我应该解释一下原因。
当您看到这样的方法时,
它并不要求提供类数组,而是需要类作为参数。它称为 varargs,您可以在 http:// /docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
Try this instead:
EDIT: Sorry I should have explained why.
When you see a method like this
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