I am using Java spring boot for business. It's fascinating to be able to easily get set the properties written in the data class When there were a lot of properties to handle, it became a getter festival, which sometimes hindered the visibility of the code. Besides, I was also downcasting the mold, so in the case of this mold. .. .. In the case of that type. .. .. And so on, it was going to be difficult again. So I decided to use MethodUtil for refactoring.
AccessProperly.java
@SuppressWarnings("unchecked") //necessary
private static<T> T getProperty(Object o, String MethodName) {
Method method = MethodUtils.getAccessibleMethod(o.getClass, methodName);
if (method == null) {
return null;
}
try {
return(T) method.invoke(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//Use
String str = getProperty(object, "getPropertyName"); // object.Same as GetPropertyName
//Data class fields can be retrieved
This is useful when you need a lot of conditional branching for each instance. Besides that, if you want to simplify the access to the method only in the class There are various uses. Since the property acquisition method of the object is called frequently, I would like to deepen my understanding. I'm not very familiar with it yet (I don't have many detailed articles ...) If you are familiar with it, I would appreciate it if you could write an article.
Recommended Posts