[Java] – Use reflection to call methods

Below is an example to show in a simple way how to we can use reflection to call methods.

First, we will implement a common User Class :

 

public class User{
    private String name;
    private String email;
    private String password;

    private User(){}

    public User(String password, String name, String email) {
        this.password = password;
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    // Methods with Validator in the name
    public boolean emailValidator(){
        return this.email.contains("@");
    }

    public boolean passwordValidator(){
        return this.password.length() > 4;
    }

    // This here is only to show to you that this
    // method don't will be called in this example.
    public boolean otherExternalValidator(boolean value){
        return value == true;
    }
}

So, we have 3 methods with the word “Validator”. In this case, we want call only public methods that ends with “Validator”, don’t receive parameters and return a boolean value. 

Let’s go to see de code :

 /*
 * @param obj
 * @throws Exception
 */
public void callValidatorsMethods(Object obj) throws Exception{
    Class<?> clazz = obj.getClass();
    // Interation in all public methods of the class
    for(Method m : clazz.getMethods()){
        if(m.getName().endsWith("Validator") &&
                // Here we put a condition for get
                // the methods that return a boolean,
                // also can be a lot of types like
                // a void return(no return).
                m.getReturnType() == boolean.class &&
                // We can validate the parameters of the method
                // remember in Java Language we can have a lot
                // of methods with the same name but with
                // diferents parameters (size or types)
                m.getParameterTypes().length == 0){
            // Here we are invoking the method that you found
            // in the class
            Boolean result = (Boolean) m.invoke(obj);
            System.out.println("Method Name: " + m.getName() 
                               + "Result: " + result);
        }
    }
}

Now, we will implement a code to call:

@Test
public void testCallValidatorsMethods() throws Exception {
    String name = "Name user";
    String email = "validaEmail@email.com";
    String password = "123123123";
    User validUser = new User(password, name, email);
    callValidatorsMethods(validUser);

    System.out.println("***************************");
    System.out.println("The user with no valid email ");
    name = "Name user";
    email = "validaEmail";
    password = "123123123";
    User UnValidUser = new User(password, name, email);
    callValidatorsMethods(UnValidUser);

}

Bellow is the console log : 

Screen Shot 2016-06-06 at 3.29.48 PM

Important : 

We can call private methods by reflection, the same way, we can get attributes which are declared like private in the class.

Class<?> clazz = obj.getClass();

// Return all public methods
obj.getClass().getMethods();

// Return all declared methods in the class ( public or not )
obj.getClass().getDeclaredMethods();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s