java 通过方法“迭代”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3316582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:16:20  来源:igfitidea点击:

"Iterating" through methods

javamethodscallmethod-call

提问by

Let's say I've got a Java object that's got among others the following methods:

假设我有一个 Java 对象,其中包含以下方法:

public String getField1();
public String getField2();
public String getField3();
public String getField4();
public String getField5();

Is there a way to iterate through these methods and call 'em like the following code?

有没有办法遍历这些方法并像下面的代码一样调用它们?

String fields = "";
for(int i = 1; i <= 5; i ++){
   fields += object.(getField+i) + " | ";
}

Thank you for your upcoming ideas.

感谢您即将提出的想法。

采纳答案by Sanjay Manohar

There is a way using reflection:

有一种使用反射的方法:

try{
  Method m= object.getClass().getMethod("getField"+String.valueOf(i), new Class[]{});
  fields+=(String)m.invoke(object);
}catch(...){...}

However:This business all smells of bad coding practice! Can't you rewrite all the getFieldN()methods like this?

然而:这项业务充满了糟糕的编码实践!你不能getFieldN()像这样重写所有的方法吗?

String getField(int fieldNum)

You are asking for trouble by creating numbered methods. Remember that reflection is slow and should only be used when String-based method calls are absolutely essential to the flow of your program. I sometimes use this technique for user-defined scripting languages where you have to get a method by name. That isn't the case at all here, your calls are integer-indexed. You should therefore keep the integer as a parameter.

您通过创建编号方法来自找麻烦。请记住,反射很慢,并且只应在基于字符串的方法调用对程序流程绝对必要时使用。我有时将这种技术用于用户定义的脚本语言,您必须按名称获取方法。这里根本不是这种情况,您的电话是integer-indexed。因此,您应该保留整数作为参数。

If this is legacy code and you are absolutely unable to change this bad coding, then you might be better off creating a new method getMethod(int)as above to wrap the existing methods, that just delegates to the numbered getMethodN()methods.

如果这是遗留代码并且您绝对无法更改这种糟糕的编码,那么您最好创建一个getMethod(int)如上所述的新方法来包装现有方法,该方法仅委托给编号的getMethodN()方法。

回答by Alberto Zaccagni

Class yourClass = YourClass.class;
for (Method method : yourClass.getMethods()){
    method.invoke(obj, args);           
}

See this guidefor reference.

请参阅本指南以供参考。

回答by stacker

To be able to select specific fields and order you should specifiy them i.e. by a list of field names.

为了能够选择特定的字段和顺序,您应该通过字段名称列表来指定它们。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.StringTokenizer;

public class CsvReflect {
    int a = 10;
    String b = "test";
    Date d = new Date();

    public int getA() {
        return a;
    }

    public String getB() {
        return b;
    }

    public Date getD() {
        return d;
    }

    public static String toCsv(Object obj, String fields, String separator) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        StringBuilder sb = new StringBuilder();
        StringTokenizer st = new StringTokenizer(fields,",");
        while ( st.hasMoreElements() ) {
            String field = st.nextToken();
            Method getter = obj.getClass().getMethod("get"+ field, new Class[]{});
            String val = "" + getter.invoke(obj, new Class[]{});
            sb.append( val );
            if ( st.hasMoreElements() ) {
                sb.append(separator);
            }
        }
        return sb.toString();
    }
    public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        CsvReflect csv  = new CsvReflect();
        System.out.println( csv.toCsv( csv ,"A,B,D", "|" ));
    }
}