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

查看:26
本文介绍了如何循环 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,Item 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天全站免登陆