Java: get all variable names in a class

前端 未结 4 2065
醉酒成梦
醉酒成梦 2020-11-27 12:40

I have a class and I want to find all of its public fields (not methods). How can I do this?

Thanks!

4条回答
  •  春和景丽
    2020-11-27 13:06

    You can use any of the two based on your need:

    Field[] fields = ClassName.class.getFields(); // returns inherited members but not private members.
    Field[] fields = ClassName.class.getDeclaredFields(); // returns all members including private members but not inherited members.
    

    To filter only the public fields from the above list (based on requirement) use below code:

    List fieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPublic(field.getModifiers())).collect(
        Collectors.toList());
    

提交回复
热议问题