如何在android上创建带有反射的TextView?

发布于 01-01 01:54 字数 699 浏览 2 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏花。依旧2025-01-08 01:54:05

试试这个:

Constructor ct = cls.getConstructor( context.getClass() );

编辑:抱歉,我应该解释一下原因。

当您看到这样的方法时,

getConstructor(Class... parameterTypes) 

它并不要求提供类数组,而是需要类作为参数。它称为 varargs,您可以在 http:// /docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文