Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass method name dynamically in java

I have an Class like as follows

public class Test
{
     private Long id;
     private Long locationId;
     private Long anotherId;

    public Long getId() {
    return id;
}


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


public Long getLocationId() {
    return locationId;
}


public void setLocationId(Long locationId) {
    this.locationId = locationId;
}


public Long getAnotherId() {
    return anotherId;
}


public void setAnotherId(Long anotherId) {
    this.anotherId = anotherId;
}
}

I have used following methods in various places to find the matched object by using id,locationId or anotherId

public Test getMatchedObject(List<Test> list,Long id )
{

          for(Test vo : list)
                if(vo.getId() != null && vo.getId().longValue() == id.longValue())
                return vo;
}

public Test getMatchedLocationVO(List<Test> list,Long locationId )
{

          for(Test vo : list)
                if(vo.getLocationId() != null && vo.getLocationId().longValue() == locationId.longValue())
                return vo;
}

public Test getMatchedAnotherVO(List<Test> list,Long anotherId )
{

          for(Test vo : list)
                if(vo.getAnotherId() != null && vo.getAnotherId().longValue() == anotherId.longValue())
                return vo;
}

I used different method for each parameter to find out the object.Is there any way i can pass method name dynamically?

Thanks in advance...

like image 830
PSR Avatar asked Mar 15 '14 04:03

PSR


2 Answers

You need to use reflection to do this.

import java.lang.reflect.*;

Method method = obj.getClass().getMethod(methodName);

then invoke it with method.invoke(obj, arg1, arg2);

This is somewhat similar to the way call works in javascript (if you're familiar with that), except instead of passing the context, you're passing the object and a reference to it's method.

like image 67
Greg Jennings Avatar answered Oct 28 '22 10:10

Greg Jennings


You can do this with reflection, but it's probably not the best solution to your original problem as reflection is meant for use by programming tools. You should look into using other tools, like polymorphism and inheritence, that can provide similar functionality.

like image 43
Code-Apprentice Avatar answered Oct 28 '22 09:10

Code-Apprentice