0

Is it possible to write a method or a way to print parameters of any method? I mean assume that I have two methods like

calculate(int a,int b) {}

notifyResult(int type){}

so I want a method that print "a" and "b" upon calculate method invocation same things will happen upon invoing notifyResult print "type".

I know that using reflection or AOP tech can help me? Is there an other way to do that?

Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141

3 Answers3

3

Since Java 8 you can obtain the name of method argument.

To do that you will have to compile your code with option -parameters.

Then form instance of [Executable] class (Method or Constructor) you can use method getParameters() to obtain array of Parameter instances. The method getName() will resolve you the names.

private void example(Class<?> type) {

 for(Method method : type.getMethods()){
   for(Parameter parameter : getParameters()) {
       System.out.println("%s",parameger.getName());
   }
  }
}
1

There is no direct method to do this. I mean, there is no java API that can retrieve you parameters.

You can however use the the following approaches.

  1. Add log message in the beginning of each method. Print all arguments manually.
  2. Use byte code engineering
  3. Use (dynamic) proxy

Examples of byte code engineering libraries are ASM, CGLIB, Javassist. Example of higher level, AOP library is AspectJ.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

you can do that in Java 8:

Class<String> someClass = String.class;
for (Method someMethod : someClass.getDeclaredMethods()) {
   for (Parameter p : someMethod.getParameters()) {
      System.err.println("  " + p.getName());
   }
}

And to have and over view look here

Community
  • 1
  • 1
Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118