0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java MethodUtilでプロパティアクセスの処理をリファクタリング

Posted at

Java MethodUtilについて

 Java spring bootを業務で使っています。データクラスに書いたプロパティを簡単にget setできるのは魅力的ですが
どうも扱うプロパティが多い場合にgetter祭りになってしまいコードの見通しに支障をきたすことがありました。その上、型のダウンキャストもしていたため、この型の場合は。。。あの型の場合は。。。など、、、また大変なことになっていました。なのでMethodUtilを使ってリファクタリングを実施することにしました。

使い方

AccessProperly.java
 @SuppressWarnings("unchecked") // 必要
 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);
   }
} 

// 用途
    String str = getProperty(object, "getPropertyName"); // object.GetPropertyNameと同じ 
   // データクラスのフィールドが取得できる

インスタンスごとに条件分岐がたくさん必要な場合に役に立ちます。それ以外にもメソッドへのアクセスをクラス内だけで簡潔させたい場合
とか用途はいろいろあります。オブジェクトのプロパティ取得メソッドの呼び出しは頻繁に行うのでより理解を深めていきたいと思います。
まだ、あまり詳しくないので(詳しい記事があまりない。。。)詳しい方いましたら記事にしていただければ幸い極みです笑

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?