-2

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

For example:

public class FooClass {

    String barMethod() {
        return "baz"; 
    }
}
System.out.println(FooClass.barMethod()) //Prints "baz"

How can I 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.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Rothin Sen
  • 444
  • 4
  • 8

2 Answers2

0
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));           
}
aviad
  • 8,229
  • 9
  • 50
  • 98
  • What if you don't have any args? – Rothin Sen Nov 02 '22 at 21:31
  • then, `args = null;` ) – xerx593 Nov 02 '22 at 21:35
  • Maybe specify what `obj` is. Also, this particular algorithm assumes you want to call and print every single public method that the class has, rather than a select few. But it demonstrates the general idea! – Thomas Kåsene Nov 02 '22 at 21:35
  • Getting `java.lang.IllegalArgumentException: wrong number of arguments` with `args = null` – Rothin Sen Nov 02 '22 at 21:36
  • Without `args` also works, ie `method.invoke(obj)`. But still getting the same `IllegalArgumentException ` – Rothin Sen Nov 02 '22 at 21:42
  • If you're copying this algorithm, you must keep in mind that it passes the arguments (or lack thereof) to all the methods, and very likely, the methods of the class don't all have the same number of parameters. I'm guessing that's the reason it fails - because of a mismatch in arguments and parameters. – Thomas Kåsene Nov 02 '22 at 21:54
  • Got it, there were certain functions which are implicitly part of the class, like `wait`, `equals` which accept a single param. Only for those I was getting the above exception. – Rothin Sen Nov 02 '22 at 21:54
  • There's another method that maaay be more useful to you than `getMethods()`, and that is `getDeclaredMethods()`. It returns all methods a class and its interfaces declare, but not the ones it merely inherits from its superclasses. – Thomas Kåsene Nov 02 '22 at 22:03
0

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.

Thomas Kåsene
  • 5,301
  • 3
  • 18
  • 30