PSR PSR - 24 days ago 17
Java Question

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...

Answer

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.

Comments