mardi 14 février 2023

trying to set a member ArrayList using reflection

I am trying to modify an object with an Arraylist of objects using reflection.

I understand that I cannot get the type of the objects in the ArrayList, but I (think) I am using an annotation to handle that part. I am setting the field accessibility.

I am declaring the list of stuff in the class using annotations.

@TableAnnotation(type = PhoneNumber.class)
protected List<PhoneNumber> phoneNumbers = new ArrayList<>();
@TableAnnotation(type = Address.class)
private List<Address> addresses= new ArrayList<>();
private List<Role> roles= new ArrayList<>();

... Later in the same class I try to set them:

public void setMemberTable(List<Table> tables, String memberName) throws IllegalAccessException {
    Class t = getClass();
    for (Field field : getClass().getDeclaredFields()) {
        if (field.getName() == memberName) {
            field.setAccessible(true);
            List array = (List)field.get(this.getClass()); <<<=========== Here is where it is throwing
            ArrayList arrayList= (ArrayList)field.get(this.getClass());
            //array.add(tables.get(0));
            System.out.println();
        }
    }
}

Here is the Annotation that seems to be working:

package com.test.database.helpers;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface TableAnnotation {
    Class< ?> type();
    boolean allowNull() default false;
}

This throws:

java.lang.IllegalArgumentException: Can not get java.util.List field com.test.database.entities.Person.phoneNumbers on java.lang.Class

I tried making the member variable public, but that had no affect. I need help to be able to set the member variables in setMemberTable().





Aucun commentaire:

Enregistrer un commentaire