vendredi 14 février 2020

Can I pass an object of a superclass in the invoke method while traversing through the methods of subclass via Java Reflection?

So let say I have a Person class which is the super class--> looks something like this:

public class Person {
    private String firstName;
    private String lastName;
    private String adhaarID;
    private int employeeID;


    public Person(String firstName, String lastName, String adhaarID, int employeeID) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.adhaarID = adhaarID;
        this.employeeID = employeeID;
    }

    public Person() {
    }

    public String getFullName()
    {
        return firstName+" "+lastName;
    }


    public String getFirstName()
    {
        return firstName;
    }



    public String getAdhaarID() {
        return adhaarID;
    }

    public String getLastName()
    {
        return lastName;
    }

    public int getEmployeeID() {
        return employeeID;
    }


}

And I have a sub class Employee which extend class Person and have no new method (other than what Class Person already have). In the worst case it gonna have all the methods that class Person have. In all its method the class Employee calls its super methods:---> looks something like this:

public class Employee extends Person {

    public Employee(String firstName, String lastName, String adhaarID, int employeeID) {
        super(firstName, lastName, adhaarID, employeeID);
    }
    public String getFullName() {
        return super.getFullName();
    }
    public String getAdhaarID() {
        return super.getAdhaarID();
    }
    public String getLastName() {
        return super.getLastName();
    }
    public int getEmployeeID() {
        return super.getEmployeeID();
    }
}

Now I am traversing through all the method of Class Employee through java Reflection. and I have Class Person object named person. I am passing that object to invoke the method. Like lets say getAdhaarID of Employee class is invoke on person then the value stored in person object should be returned. How should I do it. This does not work (see below):

Class<?> clazz = Employee.class;
    Method[] arrayOfMethods = clazz.getDeclaredMethods();
    for(Method method : arrayOfMethods)
    {
        String methodReturnValue = method.invoke(person,null).toString();

    }

This given an error Person cant be cast to Employee.





Aucun commentaire:

Enregistrer un commentaire