0

Good Morning. I'm getting the values from the fields of a class by reflection. I'm getting the object by parameter, but when I show the value I got, it comes in blank. I'm getting the attribute, but not the value. From what I noticed, it looks like it is not catching the instance of the object that was passed. Thanks for your help.

public static void transformarCamposCaixaAlta(BaseModel bm) {
    Class<?> classe = bm.getClass();
    for(Field item : classe.getDeclaredFields()) {
        item.setAccessible(true);

        if (item.getType() == BaseModel.class) {
            try {
                transformarCamposCaixaAlta((BaseModel) item.get(bm));
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (item.isAnnotationPresent(FieldUpperCase.class)) {
            try {
                if(item.get(bm) != null) {

                    System.out.println("Valor: "+ item.get(bm).toString() + " Tipo: "+ item.getName());
                    System.out.println("------");
                    item.set(bm, ((String)item.get(bm)).toUpperCase());
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}
Kbca
  • 3
  • 2
  • 1
    ***"...it comes in blank"*** can you elaborate, what is that for a data type? – ΦXocę 웃 Пepeúpa ツ May 17 '17 at 11:49
  • Have you tried with a [mcve] ? This looks good for me so check the instance used maybe – AxelH May 17 '17 at 11:53
  • Yes, i tested with minimal example and functional. – Kbca May 17 '17 at 11:56
  • Please provide [mcve] with a clear statement of what is actual and expected behaviour. – Jaroslaw Pawlak May 17 '17 at 12:05
  • By the way, if you want to check every type `item.getType() == BaseModel.class` would not be able to manage the subclass. Loop throuth [`Class.getGenericSuperclass`](https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getGenericSuperclass()) could help, – AxelH May 17 '17 at 12:15
  • @AxelH If I think I understand what you're driving at there, the [Class.isAssignableFrom()](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isAssignableFrom-java.lang.Class-) method is probably easier. – Gimby May 17 '17 at 12:21
  • @Gimby, that's his name !! I couldn't find it. But if I remember and understand the doc, it should be called like `BaseModel.class.isAssignableFrom(item.getType())` (it is check if the instance is a superclass of the parameter, not the other way around ;) ) – AxelH May 17 '17 at 12:23
  • @AxelH you would be correct – Gimby May 17 '17 at 12:47
  • @AxelH, I using the getGenericSuperClass, it was giving NullPointer error. I was doing the check this way: item.getType (). GetGenericSuperClass () == BaseModel.class. – Kbca May 17 '17 at 12:59
  • @kbca I need to check what could throw an NPE but like we said with Gimby, this is not the best approch, using `BaseModel.class.isAssignableFrom(item.getType())` works better. I will do some checks in a couple of hours, if you can post a [mcve] for us to test your problem (post a small class to check) – AxelH May 17 '17 at 14:02

2 Answers2

0

I would suggest trying to simplify your example and printing or logging at each step to see where it's going wrong. Without your class or annotations it's a little difficult to say exactly, but everything you've posted looks correct. Are you able to post your BaseModel class and annotation, or a simplified example like below if they are complex classes.

Maybe this basic example will help you get on the right track:

public static void basicReflection(Object obj) throws IllegalAccessException {
    Class<?> objClass = obj.getClass();
    System.out.println("obj: " + obj.getClass());

    Field[] fields = objClass.getDeclaredFields();
    for(Field field : fields) {
        field.setAccessible(true);
        System.out.println("Field: " + field.getName() + " value: " + field.get(obj));
        if (field.getType() == Bar.class) {
            System.out.println("Field is a Bar");
        }
    }
}

Some basic POJO:

public class Foo {
    public Foo(){}
    private Integer someInt = 123;
    private Long someLong = 987654321L;
    private String someString = "qwertyuiop";
    private Bar bar = new Bar();
}

Example of calling the class doing reflection:

public class Main {
    public static void main(String[] args) throws Exception {
        Foo foo = new Foo();
        basicReflection(foo);
    }
}

Resulting console output:

obj: class com.kaitait.reflection.Foo
Field: someInt value: 123
Field: someLong value: 987654321
Field: someString value: qwertyuiop
Field: bar value: com.kaitait.reflection.Bar@61bbe9ba
Field is a Bar

You might also find this post helpful.

Community
  • 1
  • 1
Kai
  • 1,709
  • 1
  • 23
  • 36
  • my class BaseModel is superclass, all objects models extended BaseModel, which only has the attributes common to models such as: dateRegistration. I call method: transformarCamposCaixaAlta before saving in GenericDao, to transform the fields with the annotation in uppercase. – Kbca May 17 '17 at 13:29
  • Have you tried without the annotation. I think that might be where your issue is. – Kai May 17 '17 at 21:41
  • Thanks a lot for the help @Kai, I used the instanceof to check each object, I do not know why I could get the instance of the object and had a variable class that I put inside one of the while for each interaction it gets the superClass until it is null . Many thanks again for the help. I could not put the code here in this answer, but I put it as a response from the post, I think it stayed up there. :) – Kbca Jun 02 '17 at 13:18
0

Thanks a lot for the help @Kai, I used the instanceof to check each object, I do not know why I could get the instance of the object and had a variable class that I put inside one of the while for each interaction it gets the superClass until it is null . Many thanks again for the help.

Class classes = bm.getClass();

    do {
        for(Field item : classes.getDeclaredFields()) {
            item.setAccessible(true);
            try {
                if (item.get(bm) != null) {
                    if (item.get(bm) instanceof BaseModel) {
                        try {
                            if (!item.isAnnotationPresent(Transient.class))
                            transformarCamposCaixaAlta(item.get(bm));
                        } catch (IllegalArgumentException | IllegalAccessException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            if (item.isAnnotationPresent(FieldUpperCase.class)) {
                try {
                    if(item.get(bm) != null) {
                        item.set(bm, ((String)item.get(bm)).toUpperCase());
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    } while((classes = classes.getSuperclass()) != null);
Kbca
  • 3
  • 2