gpt4 book ai didi

java - 对象中的变量计数

转载 作者:行者123 更新时间:2023-12-01 10:51:11 25 4
gpt4 key购买 nike

我有一个简单的问题,我们在哪里需要对象中变量的计数:

class cot{ int I; int j; int k; }

我们需要 cot[] 上每次迭代的变量计数 (3),我们有 size() 可以用来获取对象数组列表的大小。但是如何找到对象上每次迭代的变量计数。

我们知道是三个,但是需要动态对象。

最佳答案

您可以使用反射 API。这是一个例子:

import java.lang.reflect.Field;

public class cot{
int I; int j; int k;
String str;

public int CountAllVariables(){
// get reference to own class
Class<?> clazz = this.getClass();
// return amount of all fields
return clazz.getDeclaredFields().length;
}
public int CountAllInteger(){
int result = 0;
// get reference to own class
Class<?> clazz = this.getClass();
// check all fields
for ( Field field : clazz.getDeclaredFields() ) {
// count if it is an int field
if(int.class.isAssignableFrom(field.getType()))
result++;
}
return result;
}
}

现在你可以像这样使用它:

public static void main(String[] args){
cot c = new cot();
System.out.println( c.CountAllInteger()); // prints 3
System.out.println( c.CountAllVariables()); // prints 4
}

关于java - 对象中的变量计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33892334/

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