reflection static method argument string
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);
try
ArrayList output = (ArrayList) mthd.invoke(null, (String)null);
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?
First, Your check seems weird to me: try if (pattern != null)
instead of if (pattern != "")
.
Why don't you pass the par
array, you have illegal argument exception I think. try passing arguments array.
Object[] args = {"someString / maybe null"};
ArrayList output = (ArrayList) mthd.invoke(null, args);
Obviously, your invoke call is similiar to
initdata(null);
Now, inside initdata
you do not filter the case where pattern == null
which leads us to a call
Star.find(null, 0);
We do not know the implementation of this method - if we're lucky, we get an empty collection. Otherwise, I expect a NullPointerException
either in Star.find
or later at mc.iterator()
$ javac -cp dp4j-1.2-SNAPSHOT-jar-with-dependencies.jar -Averbose -All Star.java
Star.java:12:
import com.dp4j.*;
public class Star {
public Star() {
super();
}
public static ArrayList initdata(String pattern) {
return null;
}
@Reflect()
public static void main(String[] args) throws java.lang.ClassNotFoundException, java.lang.IllegalAccessException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException, java.lang.IllegalArgumentException {
final java.lang.reflect.Method initdataWithStringMethod = Class.forName("Star").getDeclaredMethod("initdata", .java.lang.String.class);
initdataWithStringMethod.setAccessible(true);
initdataWithStringMethod.invoke("", new .java.lang.Object[1][]{null});
final java.lang.reflect.Method printlnWithStringMethod = Class.forName("java.io.PrintStream").getDeclaredMethod("println", .java.lang.String.class);
printlnWithStringMethod.setAccessible(true);
printlnWithStringMethod.invoke(System.out, new .java.lang.Object[1][]{"Varargs + reflection? No problem"});
}
}
public static void main(String args[]) {
^
$ java Star
Varargs + reflection? No problem
精彩评论