java - 如何在Java中循环一个类属性?

标签 java attributes loops

如何动态循环java中的类属性。

例如:

public class MyClass{
    private type1 att1;
    private type2 att2;
    ...

    public void function(){
        for(var in MyClass.Attributes){
            System.out.println(var.class);
        }
    }
}

这在 Java 中可行吗?

最佳答案

没有语言支持可以满足您的要求。

您可以在运行时使用反射以反射方式访问类型的成员(例如,使用 Class.getDeclaredFields() 来获取 Field 的数组),但取决于您要执行的操作,这可能不是最佳解决方案。

另见

相关问题


示例

这是一个简单的示例,仅展示反射的部分功能。

import java.lang.reflect.*;

public class DumpFields {
    public static void main(String[] args) {
        inspect(String.class);
    }
    static <T> void inspect(Class<T> klazz) {
        Field[] fields = klazz.getDeclaredFields();
        System.out.printf("%d fields:%n", fields.length);
        for (Field field : fields) {
            System.out.printf("%s %s %s%n",
                Modifier.toString(field.getModifiers()),
                field.getType().getSimpleName(),
                field.getName()
            );
        }
    }
}

上面的代码片段使用反射来检查 class String 的所有声明的字段;它产生以下输出:

7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER

Effective Java 2nd Edition,第 53 条:首选接口(interface)而不是反射

以下是本书的节选:

Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:

  • You lose all the benefits of compile-time checking.
  • The code required to perform reflective access is clumsy and verbose.
  • Performance suffers.

As a rule, objects should not be accessed reflectively in normal applications at runtime.

There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.

关于java - 如何在Java中循环一个类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3333974/

相关文章:

C# 与 Java?

ruby - 如何增强 ruby​​ 中的 attr_accessor?

java 如何从字符串向对象添加变量

当属性值不同时XSLT合并节点

php - 在while循环中从不同的表中获取数据

java - 使用嵌套扫描仪检查空白输入,但必须按两次 [Return] 键

java - 格式转换出现问题,出现奇怪的错误

java - 清除 Thread.interrupt() 标志的方法

java - java是否有任何机制让VM在不使用javaagent等的情况下跟踪自身的方法调用?

javascript - 如何使用javascript更改html中的属性