pez_betta
pez_betta

Reputation: 69

Java Reflection. Access the value of a field

I am trying to complete a program with Java Reflection. I have a problem with this part. I can not get the value of the field I am looking for.

Field [] fx = ArrayUtils.addAll(c.getDeclaredFields(),c.getFields());
for (int j = 0; i < fx.length; j++){
    System.out.println(fx[j].toString());
    if( fx[j].isAnnotationPresent(Searchable.class)){
        Searchable ann = fx[j].getAnnotation(Searchable.class);
        System.out.println(ann.field() + " " + fx[j].getGenericType());
        if (ann.field().equals(field)){
    System.out.println ("Found it!");
    try {
        fx[j].setAccessible(true);
        System.out.println((String)fx[j].get(c));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    break;
        }
    }
}

With this code I get this message:

java.lang.IllegalArgumentException: Can not set java.lang.String field store.model.Book.publisher to java.lang.Class

Any idea how I can do it? Thanks a lot in advance.

Upvotes: 1

Views: 109

Answers (2)

Krzysztof Cichocki
Krzysztof Cichocki

Reputation: 6414

The error tells you, that you try to instert a String object in to the field that store the Class object.

and it is probably here:

System.out.println((String)fx[j].get(c)); // the c is a Book.class, it should a Book instance object.

Upvotes: 0

Phil Anderson
Phil Anderson

Reputation: 3146

In this line...

System.out.println((String)fx[j].get(c));

The variable c is of type Class and not of type Book. You need to pass get() an instance of Book.

Upvotes: 1

Related Questions