Leon Armstrong
Leon Armstrong

Reputation: 1303

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. This code will run inside of loadLbl().

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             
     }
}

Upvotes: 0

Views: 159

Answers (3)

Raju Sharma
Raju Sharma

Reputation: 2516

you could change from Human.class to reference object like new Human(), it should work.

like below :

Field[] fields=new Human().getClass().getDeclaredFields();

Edited :

Or dont use additional method getClass() in your code.

like below:

 Field[] fields=Human.class.getDeclaredFields();

Upvotes: 1

BIZ
BIZ

Reputation: 113

I think the answer from Raju Sharma is correct, or maybe your question isn't clear enough. The full function will be like that.

public void loadLbl()
    {
        // load all Label only
        Field[] fields = new Human().getClass().getDeclaredFields();
        for (Field field : fields)
        {
            if (field.getType().equals(Label.class))
            {
                System.out.println(field.getName());
            }
        }
    }

Upvotes: 0

LifeApi
LifeApi

Reputation: 56

Class  aClass = MyObject.class
Field field = aClass.getField("someField");

MyObject objectInstance = new MyObject();

Object value = field.get(objectInstance);

field.set(objetInstance, value);

Upvotes: 0

Related Questions