How to get all Field info in a Class in Java Reflection?

This is continuing article of my previous post. In this article we will see how can we retrieve Class Related Information using Java Reflection .We will see Filed Names .
Spatial Note : I will make a separate reflector utility class where we input a target class in its constructor and we will retrieve information using separate method. In this way ,we can isolate our needs. Please see this before start.

How to get all declared Fields inside of a class? This means , we will get the fields names which are declared inside of the class(public , private, default, protected). This is similar to what we did while method name extraction.
   1:  public String[] getAllOwnFieldNames(){
   2:          ArrayList<String> allFields = new ArrayList<String>();
   3:          for(Field aField : myClass.getDeclaredFields()){
   4:          allFields.add("Field Name : "+aField.getName()+" , Full Name : "+aField.toString());
   5:          }
   6:          return allFields.toArray(new String[allFields.size()]);
   7:      }
How to get all Fields accessible from of a class (which includes inherited fields of its own, super class and full hierarchy)?
That means , we will get fields which are included in the class and the method which are taken from its parent class.(following full hierarchy)
   1:  public String[] getAllAccessableFields(){
   2:          ArrayList<String> allFields = new ArrayList<String>();
   3:          for(Field aField : myClass.getFields()){
   4:              allFields.add("Field Name : "+aField.getName()+" , Full Name : "+aField.toString());
   5:          }
   6:          return allFields.toArray(new String[allFields.size()]);
   7:      }

Note : in both case, I used getName(), and toString() get full information. And , for both scenarios we can get access to the fields by specific names.
myClass.getDeclaredField("StingName");
myClass.getField("StringName");
And, we need to know the field name .

This is class related post where we can access fields. I will provide filed specific post separately.

Thanks..:)

No comments:

Post a Comment