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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.