PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

[FIXED] How to get names of all private data members in a class

 October 20, 2022     class, datamember, java, private     No comments   

Issue

I need a function that will return the names of all the private data members in my class as strings (perhaps in an array or list?), where each string is the name of a private, non final data member in my class. The non final condition is optional, but it would be nice.

1) Is this even possible? I think there is a way to retrieve all method names in a class, so I think this is possible as well.

2) I know I am asking for a hand out, but how do I do this?

EDIT

I have NO idea where to begin.

It seems java.lang.reflect is a good place to begin. I have started researching there.


Solution

This should do the trick. Basically you got in a List all the fields of your class, and you remove the one who are not private. :

public static void main(String [] args){
    List<Field> list = new ArrayList<>(Arrays.asList(A.class.getDeclaredFields()));

    for(Iterator<Field> i = list.iterator(); i.hasNext();){
        Field f = i.next();
        if(f.getModifiers() != Modifier.PRIVATE)
            i.remove();
    }
    for(Field f : list)
        System.out.println(f.getName());
}

Output :

fieldOne
fieldTwo

Class A :

class A {
    private String fieldOne;
    private String fieldTwo;

    private final String fieldFinal = null;

    public char c;
    public static int staticField;
    protected Long protectedField;
    public String field;
}


Answered By - user2336315
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing