jeudi 21 décembre 2017

Java - get a class attribute name when get Method is called

Can anyone please clarify me, if it is possible to get a class attribute name when I call get/set method of the class in java.
I saw something on online that it is possible to get class attribute name using Reflection concept.

My situation:
Trying to write a method that checks the value of the attribute for null/empty and return the attribute name in case the attribute value is null/empty.

example:

Class:

public class MyClass {
  private appName;

  public void setAppName(String appName) {
  this.appName = appName;
  }

  public String getAppName() {
  return this.appName;
  }
}

Validation Method:

public String validateForNull(MyClass myclass) {
   String name = myclass.getAppName();
   if(name == null || name.isEmpty()) {
   return //here I want to return attributeName which will be "appName"
   }
}

I realized returning the constant string that represent attribute name will be lot easier and neat way for the approach. But I was wondering if I can do it as a generic way where validate method takes the class object and check all/specified attributes for null/empty and return attribute name in case null/empty value.

Thanks





Aucun commentaire:

Enregistrer un commentaire