获取类中的所有变量名 [英] Get all variable names in a class

查看:68
本文介绍了获取类中的所有变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我想找到它的所有公共字段(不是方法).我该怎么办?

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 文字实际上表示

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.

这篇关于获取类中的所有变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆