Home > OS >  How to print a Method name along with it's return value?
How to print a Method name along with it's return value?

Time:11-03

I have FooClass with barMethod() that returns "bazz" string. How to print in console barMethod along with bazz?

For eg

public class FooClass {


    String barMethod() {
        return "baz"; 
    }

}


System.out.println(FooClass.barMethod()) //Prints "baz"

How to print the following?

customPrint(FooClass.barMethod()) //barMethod = baz

Note: I can't modify barMethod() or FooClass

Found How to get a string name of method in java on stack overflow but it isn't what I'm looking for.

CodePudding user response:

You should be able to use the reflection API to call the method. For a brief introduction and examples, see here. Also, see aviad's answer.

CodePudding user response:

Class yourClass = YourClass.class;
for (Method method : yourClass.getMethods()){
    // format the output as you wish using something like:  
    System.out.println(method.getName()   " "   method.invoke(obj, args));           
}
  • Related