简体   繁体   中英

How do I know if a class has a method in java and how do I invoke it

I need to know if a java class has the method

public double getValue() 

if there is a method. I need call the method.

Sorry, I forgot to say that this need to do at runtime

You could use Class.getMethod() to get the Method object, and then Method.call() to invoke the method.

getMethod() will throw NoSuchMethodException if the class doesn't have a method with the requested name and signature.

You need to get the class, and then the methods from the class. Assume angst is your object.

Object angst = new Object();
Method[] methods= angst.getClass().getMethods();
for(i=0; i<methods.length; i++) {
    if(methods[i].getName().equals("getValue") {
        //some boolean stuff
    }
}

您必须使用Java Reflection

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