dimanche 5 juin 2016

How to get parameter types using method name in java?

Say, I have a class.

class Person{
    private int id;
    private String name;

    public void setId(int id){
        this.id = id;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getId(){
        this.id = id;
    }

    public String getName(){
        this.name = name;
    }
}

Like this, I have more than one data transfer classes. And I want to have a class where it will take method name(String.class) and parameter value(Object.class) dynamically as shown in the below snippet.

class Mapper{
    private Person person = new Person();
    private Method method = null;
    public void map(String methodName, Object parameterValue){
         // 1. Get the method using methodName.
         // 2. Get the method's parameter type.
         // 3. Type cast 'parameterValue' to parameter type.
         // 4. Call the method on 'person' object by passing type cast value
         //    from the 3-step(above).
    }
}

I have tried searching on it. I got the results on Reflection API as shown in the snippet below.

Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
   System.err.println(m.getName());
   int paramCount = m.getParameterTypes().length;
   for (int i = 0;  i < paramCount;  i++) {
      System.err.println("  arg" + i);
   }
}

But, this kind of approach doesn't meet my need. Hope you understand.





Aucun commentaire:

Enregistrer un commentaire