“迭代”通过方法

发布于 2024-09-11 06:14:37 字数 369 浏览 6 评论 0原文

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

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

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

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

感谢您即将提出的想法。

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

燃情 2024-09-18 06:14:37
Class yourClass = YourClass.class;
for (Method method : yourClass.getMethods()){
    method.invoke(obj, args);           
}

请参阅本指南以供参考。

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

See this guide for reference.

撕心裂肺的伤痛 2024-09-18 06:14:37

有一种使用反射的方法:

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

但是:
这个行业充满了糟糕的编码实践的味道!
难道你不能像这样重写所有的getFieldN()方法吗?

String getField(int fieldNum)

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

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

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?

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.

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.

怪我太投入 2024-09-18 06:14:37

为了能够选择特定字段并排序,您应该指定它们,即通过字段名称列表。

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", "|" ));
    }
}

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", "|" ));
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文