0

I'm creating a validation class for my project. At the moment I'm stuck on the point that I want to invoke a method (in this case getText()) from a class that is being passed via a generic type.

Here are the codes:

In this class I created a getRules where I pass a HashMap where the key is the name of the field, and the value in the rules attached to it.

public class PlayerValidator extends FormValidator<PlayerFormPanel> {
  @Override
  protected HashMap<String, String> getRules() {
    HashMap<String, String> rules = new HashMap<>();
    rules.put("firstNameField", "required");

    return rules;
  }
}

Next I got a parent class where I got a validate method, which will iterate over the rules and check if the rule is valid or invalid.

abstract class FormValidator<T> {

  abstract HashMap<String, String> getRules();

  public void validate(T form) {
    System.out.println(form.toString());

    for (Map.Entry<String, String> field : getRules().entrySet()) {
        System.out.println(field.getKey());
        System.out.println(field.getValue());
    }
  }
}

In the generic type T I get the PlayerFormPanel object, but how would I be able to call the getText() method on the firstNameField (field.getKey())?

guidsen
  • 2,333
  • 6
  • 34
  • 55

1 Answers1

0

You should use Introspector or Reflection

for(PropertyDescriptor prop : Introspector.getBeanInfo(class).getPropertyDescriptors()){
  System.out.println(prop.getReadMethod());
}  

Possible duplicate of this question: Java Reflection: How can i get the all getter methods of a java class and invoke them

Community
  • 1
  • 1
Henrique Goulart
  • 1,815
  • 2
  • 22
  • 32