简体   繁体   中英

using Method invoke with static methods?

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() == "boolean" 
            && 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM