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

7
我有一个类,如下所示:
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查找匹配的对象:

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;
}

我针对每个参数使用了不同的方法来查找对象。有没有一种方法可以动态地传递方法名?

提前感谢...


1
听起来像是反射。 - jmj
@JigarJoshi 我对此没有了解。你能给我一个例子或者建议吗? - PSR
1
或者您可以创建一个接口,其中包含一个接受Test对象作为参数并在实现类中返回相应id值的getId方法。您也可以使用抽象类来实现它。 - Rebecca Abriam
@RebeccaAbriam,我不理解你的陈述。你能解释一下吗? - PSR
@PSR 我发了一个答案来阐述我的想法。 - Rebecca Abriam
5个回答

8
你需要使用反射来实现这个功能。
导入java.lang.reflect.*库: import java.lang.reflect.*; 获取方法对象: Method method = obj.getClass().getMethod(methodName); 然后使用method.invoke(obj, arg1, arg2);调用它。
如果你熟悉javascript中的调用方式,那么这种方法有点类似,只不过你需要传递对象和它的方法引用,而不是上下文。

obj.getClass().getMethod(methodName, arg1Class)例如:String.class - Gerson Diniz
当在setter方法中使用Lombok时,会抛出NoSuchMethodException异常。 - Salman Kazmi

2
你可以使用反射来实现这一点,但反射通常不是解决原始问题的最佳解决方案,因为反射是为编程工具设计的。你应该考虑使用其他工具,如多态和继承,它们可以提供类似的功能。

2
尽管您正在动态调用方法并且看起来像是反射,但据我所见,您正在调用访问器和嵌套访问器,这需要使用 Java Introspection API。
它支持 Java Bean API,并且可以轻松访问访问器/修改器和嵌套的访问器/修改器。
还有一些其他的库也可以简化这个过程,例如 Apache BeanUtils 和 Spring 的 BeanWrapper 类。

1

0

使用接口的可能解决方案。希望你能理解。代码不一定编译通过。由于这是在iPad上输入,格式可能有误,请见谅。

public interface IdMatcher{
  Long id;
  public boolean matches(Test obj);
}

具体类:

public class LocationIdMatcher implements IdMatcher() {
  public LocationIdMatcher(id) {
  this.id = id;
}
public boolean matches(Test obj) {
   if (obj.getLocationId() == this.id)
    return true;
   }
}

已更新匹配的VO:

public Test getMatchedVO(List<Test> list, IdMatcher idMatcher) {
  for(Test vo: list) {
   if(idMatcher.matches(vo) {
     return vo;
   }
  }
  return null;
}

使用方法:

Test vo = getMatchedVO(list, new LocationIdMatcher(locationId));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接