问题描述
我有一个如下所示的类
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;
}
}
我在各个地方使用了以下方法通过使用 id、locationId 或 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?
提前致谢...
推荐答案
你需要使用反射来做到这一点.
You need to use reflection to do this.
import java.lang.reflect.*;
Method method = obj.getClass().getMethod(methodName);
然后用 method.invoke(obj, arg1, arg2);
这有点类似于 javascript 中调用的工作方式(如果您熟悉它的话),除了不是传递上下文,而是传递对象及其方法的引用.
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.
这篇关于如何在java中动态传递方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!