2

I using the following code to get the method input parameter but I getting the wrong params for example I for set salary I want to get the type (double )and the name (salary) . what i miss here ?

public void setSalery(double salery) {
    this.salery = salery;
  }

this is the code

for (Method method : classHandle.getMethods()) {


            Class<?>[] parameterTypes = method.getParameterTypes();

            for (Class<?> class1 : parameterTypes) {

                Field[] declaredFields = class1.getDeclaredFields();
                for (Field field : declaredFields) {
                    System.out.println(field.getName());


            }
2
  • You're currently printing out the fields of the parameter types. I can't immediately find any method which will give you the parameter names... Commented Jan 17, 2013 at 7:28
  • Well, what you are asking for, I faced this few months ago. But I couldn't find any way to get the names of the parameters. Probably because they are not stored as a part of the compiled class file. I thought there might be some way, like annotating the class in some way to tell it to store the names, but I couldn't find one. Commented Jan 17, 2013 at 7:31

1 Answer 1

3

You can retrieve the parameter types but not the parameter names. They are of no significance except within the method, which at this point is opaque to you. getDeclaredFields() returns the fields in the types, not the parameter names.

To invoke such a method (using your example), assume

MyBean b = new MyBean(); // contains method setSalary(double salary)
Method m = ...           // a reference to a Method object for MyBean#setSalary(double salary)
double newSalary = ...;

Then do

m.invoke(b, new Double(newSalary));
Sign up to request clarification or add additional context in comments.

3 Comments

Actually I want at the end to find all the Set methods and to send them parameter ,there is no way to do it ? my secnario is to get method name by string and to find all the sets method and than to send them the respective data..
For that you do not need the parameter name, only its type. When you invoke the method (using Method#invoke(Object, Object...)) parameters are matched by position, not by name.
Can you provide some example please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.