0

I am writing a hibernate listener which will do some operation before and after passing to db. I have to get a value of a field using reflection. I have wrote a sample code to demonstrate my question.

public class Test {

FileAttachment  attachment = new FileAttachment();

public Test() {
    attachment.setData(new byte[1]);
}


void test() throws Exception{
    for(Field field :attachment.getClass().getDeclaredFields()) {
        if ((CloudPersistable.class).isAssignableFrom(field.getType())) {


            System.out.println("BOom");

            Class<?> x = Class.forName(attachment.getClass().getCanonicalName());
            Field f = x.getDeclaredField("data");
            f.setAccessible(true);

            CloudPersistable attachment = (CloudPersistable) f.get(f.getClass());
            System.out.println(attachment);

        }
    }


}

public static void main(String[] args)throws Exception {
     new Test().test();;


}

}

** Please help to resolve line CloudPersistable attachment = (CloudPersistable) f.get(f.getClass());

Thanks in advance..!!!

Anas Fahumy
  • 41
  • 1
  • 9
  • 1
    You have to pass to f.get the object of which you want to retriev the field value, instead of its class – QuentinC May 17 '18 at 04:06
  • Especially have a look at https://stackoverflow.com/a/38736542/1531124 . Beyond that: really really dont try to learn reflection from quickly reading its APIs. Read a good tutorial/book about it. This is complicated stuff, and **each and any** details matters. There are zillions of ways to get reflection wrong, and you dont notice until runtime. Thus: dont experiment. Do research how to do do correctly, and follow working examples, step by step, character by character! – GhostCat May 17 '18 at 04:33

1 Answers1

1

You need the object on which to read the field value. So, if you were to read the value like this:

this.attachment.data

Using reflection, you would do:

field.get(this.attachment);

Just a side note: you can get the class object for a known class by just typing Attachment.class, such that your loop would be declared as:

for(Field field : Attachment.class.getDeclaredFields())

This makes it clear that it's the exact same class that's being read (not a possibly different runtime class).

ernest_k
  • 44,416
  • 5
  • 53
  • 99