Refactor property access handling with Java Method Util

About Java Method Util

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.

How to use

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

Refactor property access handling with Java Method Util
Easy database access with Java Sql2o
Java method
java (method)
[Java] How to compare with equals method
Concurrency Method in Java with basic example
Java method
[Java] method
Run Rust from Java with JNA (Java Native Access)
Access modifier [Java]
Java8 method reference
[Java] forEach method
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
java8 method reference
[Java] Random method
[Java] split method
[Java] Consideration when handling negative binary numbers with Integer.parseInt ()
Include image in jar file with java static method
Call a method with a Kotlin callback block from Java