问题描述
我有一个类,我想找到它的所有公共字段(不是方法).我该怎么办?
I have a class and I want to find all of its public fields (not methods). How can I do this?
推荐答案
Field[] fields = YourClassName.class.getFields();
返回该类的所有公共变量的数组.
returns an array of all public variables of the class.
getFields()
返回整个类的域.如果只想在相关类中定义字段,而不是其超类,请使用 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.Class
.检查其文档以获取更多有趣的反射方法.
The YourClassName.class
literal actually represents an object of type java.lang.Class
. Check its docs for more interesting reflection methods.
上面的 Field
类为 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.
这篇关于获取类中的所有变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!