How do you invoke a static java method when one of the parameters for Method invoke invoke(Object obj, Object[] args)
, requires an object parameter?
For example
Here I have a section of code that checks a class and locates any static methods that have no parameters, a return type of Boolean and starts with the name "test". I am trying to invoke such methods to see if they return true though, and I am at odds at how to do so.for (int i = 0; i < Class.forName(name).getDeclaredMethods().length; i++) {
Method method = Class.forName(name).getDeclaredMethods()[i];
if (method.getParameterTypes().length == 0
&& method.getReturnType().getName() == "boolea开发者_JAVA技巧n"
&& method.getName().startsWith("test", 0)) {
if (Class.forName(name).getDeclaredMethods()[i].invoke()==true)
System.out.println("Test" + " " + Class.forName(name).getDeclaredMethods()[i].getName() + " " + "succeeded");
}
}
First of all you claimed that you are checking method for staticness
. But actually you are not. Use this to check for static
modifier,
Modifier.isStatic(method.getModifiers());
Now, you can pass null
as a first argument and an empty array as a second, to method.invoke()
if the method is static
with zero arguments. For example,
Class.forName(name).getDeclaredMethods()[i].invoke(null, new Object[0]);
TIP: Don't repeat Class.Forname()
every time. Store it in some variable and use it. Do the similar thing wherever appropriate.
精彩评论