反射静态方法参数字符串
public class Star{
public static ArrayList initdata(String pattern) {
ArrayList data = new ArrayList();
if (pattern != "") {
ModelCollection mc = Star.find(pattern, 0);
Iterator dataIterator = mc.iterator();
while (dataIterator.hasNext()) {
Star star = (Star) dataIterator.next();
data.add(star.getName());
Debug.trace("StarName" + star.getName());
}
}
Collections.sort(data);
return data;
}
}
我想使用反射调用 initdata 方法,我尝试编写类似这样的内容,但它不起作用:
Class c = Class.forName("com.cubiware.fyretv.application.model.Star");
par[0] = String.class;
Method mthd = c.getMethod("initdata", par);
ArrayList output = (ArrayList) mthd.invoke(null, null);
public class Star{
public static ArrayList initdata(String pattern) {
ArrayList data = new ArrayList();
if (pattern != "") {
ModelCollection mc = Star.find(pattern, 0);
Iterator dataIterator = mc.iterator();
while (dataIterator.hasNext()) {
Star star = (Star) dataIterator.next();
data.add(star.getName());
Debug.trace("StarName" + star.getName());
}
}
Collections.sort(data);
return data;
}
}
I want to invoke method initdata using reflection, I tried to write something like this , but it does not work:
Class c = Class.forName("com.cubiware.fyretv.application.model.Star");
par[0] = String.class;
Method mthd = c.getMethod("initdata", par);
ArrayList output = (ArrayList) mthd.invoke(null, null);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
当方法需要 Object 时,传递 null 不是一个好主意...
可能这会有所帮助
使用单个 null 参数调用 Java varargs 方法?
try
It's not good idea to pass null, when method expects Object...
May be this will help
Calling Java varargs method with single null argument?
首先,你的检查对我来说似乎很奇怪:尝试
if (pattern != null)
而不是if (pattern != "")
。你为什么不传递
par
数组,我认为你有非法参数异常。尝试传递参数数组。First, Your check seems weird to me: try
if (pattern != null)
instead ofif (pattern != "")
.Why don't you pass the
par
array, you have illegal argument exception I think. try passing arguments array.显然,您的调用类似于
现在,在
initdata
内,您不会过滤pattern == null
的情况,这会导致我们调用我们不知道的实现这种方法 - 如果幸运的话,我们会得到一个空集合。否则,我预计在
Star.find
中或稍后在mc.iterator()
中出现NullPointerException
Obviously, your invoke call is similiar to
Now, inside
initdata
you do not filter the case wherepattern == null
which leads us to a callWe do not know the implementation of this method - if we're lucky, we get an empty collection. Otherwise, I expect a
NullPointerException
either inStar.find
or later atmc.iterator()