vendredi 24 septembre 2021

How to invoke method on a specific definition of a class using reflection?

I am trying to pull a field via reflection that is an array of the below class.

package com.api.Person
public class Person {

    private String name;
    private int age;

    public Person() {

    }

    public void setName(String name) {
    this.name = name;
    }

    public String getName() {
    return name;
    }
    
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}
package com.client.Client
public class Client{
    ...
    People[] peoples;
    ...
}

I know how to get the field I am looking for and declare my methods. So below, obj would be my People[] and methodgetAge and methodsetAge are two methods I have defined that act on a Person class. How do I take my obj and loop through it to get individual People and call methodgetAge on each person?

Class<?> mainClass = cl.loadClass("com.client.Client");
Class<?> peopleClass = cl.loadClass("com.api.Person");
Field allPersons = mainClass.getDeclaredField("peoples");
allPersons.setAccessible(true);
Object obj = allPersons.get(mainClass);

Method methodgetAge = peopleClass .getDeclaredMethod("getAge");
Method methodsetAge = peopleClass .getDeclaredMethod("setAge", int.class);




Aucun commentaire:

Enregistrer un commentaire