java:获取类中的所有变量名 [英] java: get all variable names in a class
问题描述
我有一个类,我想找到所有的公共变量(不是函数)。我怎么能这样做?
谢谢!
I have a class and i want to find all of it's public variables (not functions). how can i do so? thanks!
推荐答案
Field[] fields = YourClassName.class.getFields();
返回该类所有公共变量的数组。
returns an array of all public variables of the class.
getFields()
返回整个类 - heirarcy中的字段。如果您希望仅在相关类中定义字段,而不是其超类,请使用 getDeclaredFields()
,并过滤 public
具有以下修饰符
的方法:
getFields()
return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields()
, and filter the public
ones with the following Modifier
approach:
Modifier.isPublic(field.getModifiers());
YourClassName.class
文字实际上代表一个 java.lang类型的对象。类
。检查其文档以获得更有趣的反射方法。
The YourClassName.class
literal actually represents an object of type java.lang.Class
. Check its docs for more interesting reflection methods.
上面的字段
类是 java.lang.reflect.Field
。您可以查看整个 java.lang.reflect
包。
The Field
class above is java.lang.reflect.Field
. You may take a look at the whole java.lang.reflect
package.
这篇关于java:获取类中的所有变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!