如何在Java中循环一个类属性? [英] How to loop over a Class attributes in Java?

查看:38
本文介绍了如何在Java中循环一个类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I loop over a class attributes in java dynamically.

例如:

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

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

这在 Java 中可行吗?

is this possible in Java?

推荐答案

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

There is no linguistic support to do what you're asking for.

您可以在运行时使用反射(例如,使用 Class.getDeclaredFields() 获取 Field),但取决于你想要做什么,这可能不是最好的解决方案.

You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.

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

Here's a simple example to show only some of what reflection is capable of doing.

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 的所有声明的字段;它产生以下输出:

The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:

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 条:首选接口而不是反射

以下是本书的节选:


Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection

These are excerpts from the book:

给定一个 Class 对象,可以获取 构造函数方法Field 实例表示类的构造函数、方法和字段.[它们] 让您反思地操纵它们的底层对应物.然而,这种力量是有代价的:

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:

  • 您将失去编译时检查的所有好处.
  • 执行反射访问所需的代码既笨拙又冗长.
  • 性能受到影响.

作为一项规则,对象不应在运行时在正常应用程序中进行反射访问.

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中循环一个类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆