如何在Java中动态传递方法名称

PSR*_*PSR 4 java reflection

我有一个如下的班级

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;
}
}
Run Code Online (Sandbox Code Playgroud)

我在各个地方使用以下方法通过使用id,locationId或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;
}
Run Code Online (Sandbox Code Playgroud)

我为每个参数使用了不同的方法来查找对象。是否有任何方法可以动态传递方法名称?

提前致谢...

Gre*_*ngs 5

您需要使用反射来执行此操作。

import java.lang.reflect.*;

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

然后用 method.invoke(obj, arg1, arg2);

这有点类似于javascript中调用的工作方式(如果您熟悉的话),除了传递上下文和对象的引用,而不是传递上下文。