使用反射动态保存类中的所有字段? (“”、“”)
我试图通过使用反射来避免对配置类的序列化进行硬编码,但我遇到了无法弄清楚任何事情的情况。这就是我正在尝试做的事情。
我有一堂这样的课
公共类配置{ 公共布尔布尔 = 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你必须使用数组吗?如果没有,您可以将对象表示为列表,这将打印整数的列表表示。
或者,您可以在运行时执行此操作。
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.
Alternatively, you could just do that at runtime.
您可以使用 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.