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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With