mardi 26 septembre 2017

How to get current class's field base on object type using reflection?

I have a class that have many Label , String and int fields. Inside a method I want to loop through all Label only. Class sample as below.

public class Human{

    Label lbl1;
    Label lbl2;
    Label lbl3;
    String str1;
    int i1;

    public void loadLbl(){
         //load all Label only
    }
}

Below is the code I working now , But couldn't get the right syntax to get the fields.

Field[] fields=Human.class.getDeclaredFields(); // get all declared fields

for(Field field:fields){
     if(field.getType().equals(Label.class)){ // if it is a String field
      field.setAccessible(true);
      //work here             
     }
}





Aucun commentaire:

Enregistrer un commentaire