gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:51:06 25 4
gpt4 key购买 nike

如何动态循环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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com