【问题标题】:How to iterate over methods of a class and then iterate over returned object and call another method ?如何迭代一个类的方法,然后迭代返回的对象并调用另一个方法?
【发布时间】:2016-06-24 16:17:13
【问题描述】:

假设我有以下课程:

public class ExampleList{
  // fields

  List<A> getAList(){}
  List<B> getBList(){}
  List<C> getCList(){}
  //A, B and C all extends class X with field num
}

public class Example{
  ExampleList getExampleList(){}
}

public class Test{
  main(){
    Example example = //from somewhere I get object;

    List<A> lA = example.getExampleList().getAList();
    List<B> lB = example.getExampleList().getBList();
    List<C> lC = example.getExampleList().getCList();

    //Currently I am doing
    if(lA != null) { 
      //iterate and call getCount(num)

    if(lB != null) { 
      //iterate and call getCount(num)

    if(lC != null) { 
      //iterate and call getCount(num)

  }

  getCount(int num) { //do something }
}

我想做的是动态迭代 ExampleList 的所有方法,并且只调用一次 getCount(num)。喜欢:

main(){
  for ( Methods mList : Methods)
     for ( X x: mList )
       getCount(x.getNum);
}

我知道我可以创建一个通用方法,它接受任何扩展 X 的列表,我可以在那里迭代每个列表并调用 getCount()。但我也希望能够迭代一个类的方法。有什么方法可以实现吗?

我知道我可以通过反射获得 getter 方法的列表。但我不知道在这种情况下如何使用它。

顺便说一句,这个问题不是关于如何使用反射获取方法列表。更多的是关于如何使用它或反射是如何工作的。

【问题讨论】:

    标签: java reflection


    【解决方案1】:

    遍历给定类的方法:

        // Get the instance of the class
        X instance = X.class.newInstance();
        // Run through all methods of the class
        for(Method m : instance.getClass().getDeclaredMethods()) {
            // The first parameter of invoke is an instance of X
            // The second parameters are the parameters to pass to the method
            m.invoke(instance, new Object[]{});
        }
        // do the call to getCount
        getCount();
    

    如果你有一个 List,只需多次调用它。

    对于使用反射,起点是https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多