使用反射动态保存类中的所有字段? (“”、“”)

发布于 2025-01-03 06:56:30 字数 438 浏览 2 评论 0原文

我试图通过使用反射来避免对配置类的序列化进行硬编码,但我遇到了无法弄清楚任何事情的情况。这就是我正在尝试做的事情。

我有一堂这样的课

公共类配置{

   公共布尔布尔 = false;
   公共 int 整数 = 1;
   公共 int[] intArray = {0, 1};

}

我想使用反射将名称和值保存到 属性字段。

<前><代码>--属性-- 布尔=假 整数=1 整数数组=0,1

名称部分非常简单。我的问题是获取每个字段的值,特别是获取每个 int[] 的值。除了数组之外,所有值都是原始值,因此 toString() 可以正常工作。

有人可以展示比 Oracle 更好的例子来帮助我吗?

I'm trying to avoid hard coding the serialization of a configuration class by using Reflection, and I've ran into a situation where I can't figure anything out. Here's what I'm trying to do.

I have a class like so

public class Configuration {

   public boolean bool = false;
   public int integer = 1;
   public int[] intArray = {0, 1};

}

I want to use reflection to save the names and values into a
Properties field.

--properties--
bool=false
integer=1
intArray=0,1

The name part is pretty simple. My issue is getting the value of each field, and especially getting the value of each int[]. Besides the arrays, all values are primitive, so toString() will work just fine.

Can anybody show better examples than Oracle and help me out?

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

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

发布评论

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

评论(2

东北女汉子 2025-01-10 06:56:30

你必须使用数组吗?如果没有,您可以将对象表示为列表,这将打印整数的列表表示。

public boolean bool = false;
public int integer = 1;
public int[] intArray = {0, 1}; // <-- This prints array's memory address
public List<Integer> intList = Arrays.asList(1, 2 , 3); // <-- This prints [1,2,3]

public static void main(String[] args) throws Exception {
     Config c = new Config();
     for ( Field f : c.getClass().getDeclaredFields() ) {
           System.out.println(f.get(c));
     }

 }

或者,您可以在运行时执行此操作。

if ( "int[]".equals(f.getType().getSimpleName() ) ) {
   // do stuff
}

Do you have to use an array ? If not, you could represent your object as a list and that will print a list representation of your integers.

public boolean bool = false;
public int integer = 1;
public int[] intArray = {0, 1}; // <-- This prints array's memory address
public List<Integer> intList = Arrays.asList(1, 2 , 3); // <-- This prints [1,2,3]

public static void main(String[] args) throws Exception {
     Config c = new Config();
     for ( Field f : c.getClass().getDeclaredFields() ) {
           System.out.println(f.get(c));
     }

 }

Alternatively, you could just do that at runtime.

if ( "int[]".equals(f.getType().getSimpleName() ) ) {
   // do stuff
}
撑一把青伞 2025-01-10 06:56:30

您可以使用 java.utils.Arrays.toString(int[] a) 方法。
要获得正确的数组类型,您可以在 Kal 的答案中使用 f.getType().isArray() 和 f.getType().getComponentType() 。

You can use java.utils.Arrays.toString(int[] a) method.
to get the right array type you can use f.getType().isArray() and f.getType().getComponentType() in Kal's answer.

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