あはは。な日記

最近はjava/.net・・・って言うより設計とか調整とかだなぁ(´・ェ・`)

目次

Blog 利用状況

書庫

日記カテゴリ

VBA

[java]reflectionを使って、引数のobjectの文字列化する。 ってやっぱり遅いんだなぁと

entityやら構造体やら、値を入れる入れ物を書くと大抵
toString()メソッドをoverrideしているかと思うわけですが、
毎回書くのは結構かったるい訳です。
DBのスキーマを元に、とかだと自動生成ツールがいろいろとあったりするわけですが、
時には自作しなければいけないもの。

で、reflectionでそこを楽にできないかなぁと調べた結果がこれ。
(下部にソース添付)
loopで10万回繰り返して、作成したentityで試してみた。
結果:
 reflectionを使用したもの:       12秒358
 普通にtoString()を実装   0秒180
 (StringBuilderで文字を組み立てたもの)


(´・ェ・`) ・・・違い過ぎる。
うーん、マシンスペックやらを省略してますけど、それでもこんなに違うとは。
utility的にreflectionを多用したら開発が楽できるかな?
と思ったのですが後のパフォーマンスチューニングに苦しみそうですね。
それにこれ、配列とかリストとか全然対応してないし。

とすると、次なる候補はvelocityなどのTemplateEngine系になりそうです。
(使用しているFrameworkのソースをみたらおもしろそうだったので)


package jp.co.ahaha.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import javax.persistence.Column;  //geronimo-jpa_3.0_spec-1.0jar を使用
public class ReflectionSample {

   /**
    * 受け取ったobjectを、 フィールド名=値 の形式でカンマ区切りにした文字列表現で返却します。
    * ただし、final と static で宣言された項目については呼び出す予定はありません。
    * また、もしそのobjectがentityである場合(=javax.persistence.Columnアノテーションが付加されている場合)
    * フィールド名の代わりに、Columnアノテーションの名前を用いて 出力します。
    * こちらは、返却される文字列には改行コードは含まれません。
    * @param value
    * @return
    */
   public static final String toValueOneLine(Object value) {
       return ReflectionSample.toValue(value,false);
   }
   /**
    * 受け取ったobjectを、 フィールド名=値 の形式でカンマ区切りにした文字列表現で返却します。
    * ただし、final と static で宣言された項目については呼び出す予定はありません。
    * また、もしそのobjectがentityである場合(=javax.persistence.Columnアノテーションが付加されている場合)
    * フィールド名の代わりに、Columnアノテーションの名前を用いて 出力します。
    * こちらは、返却される文字列の フィールド名=値のペア毎に改行します。
    * @param value
    * @return
    */
   public static final String toValueMulti(Object value) {
       return ReflectionSample.toValue(value,true);
   }

   final static String toValue(Object value, boolean multiLine) {

       //for NullException
       if (value == null) {
           return "null";
       }


       String endOfLine = "";
       if (multiLine) {
           endOfLine = "\n";
       }
       //get public field(Seasar entity)
       Field[] fields = value.getClass().getFields();
       boolean accessPrivate = false;
       if (fields == null || fields.length == 0) {
           //get normal javaBeans
           fields = value.getClass().getDeclaredFields();
           accessPrivate = true;
       }
       StringBuilder sb = new StringBuilder(1024);
       for (Field f: fields) {
           if (accessPrivate) {
               f.setAccessible(accessPrivate);
           }
           try {
               //dont get Final or Static fields
               if (!Modifier.isFinal(f.getModifiers()) &&
!Modifier.isStatic(f.getModifiers())) {
                   //columnName (fieldName)
                   sb.append(toFieldString(f));
                   sb.append("=");

                   //columnValue
                   Object temp = f.get(value);
                   if (temp == null) {
                       sb.append("null");
                   } else {
                       sb.append(temp.toString());
                   }
                   sb.append(",");
                   sb.append(endOfLine);
               }
           } catch (Exception e) {
               // catch and proceed
               e.printStackTrace(); //need log
           }
       }
       return sb.toString();
   }

   /**
    * if field has javax.persistence.Column annotation and (name is
not null) then return column.name
    * else return field name
    * @param f
    * @return
    */
   private final static String toFieldString(Field f) {
       Column c = f.getAnnotation(Column.class);
       if (c != null && c.name() != null) {
           return c.name();
       } else {
           return f.getName();
       }
   }
}

投稿日時 : 2008年12月20日 5:22

コメントを追加

# re: [java]reflectionを使って、引数のobjectの文字列化する。 ってやっぱり遅いんだなぁと 2008/12/20 5:50 インドリ

文字列検索とか色々いるからね・・・

# uchKRGxvIoGMhMqHDp 2014/07/19 16:05 http://crorkz.com/

8ictSj Appreciate you sharing, great post.Much thanks again. Much obliged.

# hdBmEeJEYXdWDLJ 2014/08/07 2:37 http://crorkz.com/

ar3Nq8 Great, thanks for sharing this article post.Much thanks again. Much obliged.

# I am regular visitor, how are you everybody? This post posted at this site is really fastidious. 2019/04/04 11:07 I am regular visitor, how are you everybody? This

I am regular visitor, how are you everybody?
This post posted at this site is really fastidious.

# ivermectin 3 mg tablet dosage 2021/09/28 16:37 MarvinLic

generic ivermectin for humans https://stromectolfive.com/# stromectol canada

# ivermectin 200mg 2021/10/31 15:34 DelbertBup

ivermectin 3mg pill http://stromectolivermectin19.com/# ivermectin cream canada cost
ivermectin over the counter canada

# ivermectin 1 cream 2021/11/02 12:07 DelbertBup

how much is ivermectin http://stromectolivermectin19.online# ivermectin 1 cream
ivermectin buy online

# ivermectin where to buy 2021/11/03 7:48 DelbertBup

ivermectin where to buy http://stromectolivermectin19.online# ivermectin generic cream
ivermectin tablets

# prednisone 5 mg tablet rx https://prednisonesnw.com/#
prednisone brand name in india 2021/11/13 9:41 Prednisone

prednisone 5 mg tablet rx https://prednisonesnw.com/#
prednisone brand name in india

# sildenafil 20 mg tablet uses 2021/12/08 11:08 JamesDat

http://viasild24.com/# sildenafil 20 mg tablet uses

# best place to buy careprost 2021/12/11 19:01 Travislyday

http://stromectols.com/ ivermectin 4

# careprost bimatoprost for sale 2021/12/14 5:26 Travislyday

http://baricitinibrx.com/ baricitinib eua fact sheet

# bimatoprost ophthalmic solution careprost 2021/12/15 0:17 Travislyday

http://bimatoprostrx.online/ bimatoprost

# stromectol prices 2021/12/16 15:25 Eliastib

jwbndb https://stromectolr.com stromectol order online

# stromectol 15 mg 2021/12/17 10:53 Eliastib

dojqil https://stromectolr.com ivermectin 80 mg

# clomiphene tablets https://clomidt.com
clomid tablets 2022/01/03 19:21 Clomid

clomiphene tablets https://clomidt.com
clomid tablets

# ivermectin price usa 2022/02/18 12:01 JamesGaf

https://stromectolst.com/# how much is ivermectin
ivermectin brand name

# ivermectin 5 2022/02/21 7:58 Jamesscons

https://stromectolis.com/# ivermectin 3mg tablets price

# XnpAgXMLdDszjWBRe 2022/04/19 13:01 markus

http://imrdsoacha.gov.co/silvitra-120mg-qrms

# doors2.txt;1 2023/03/14 14:52 KceLeOboAqAeRUMlvO

doors2.txt;1

# where to buy prednisone in australia https://prednisonepills.pro/# - prednisone 200 mg tablets 2023/06/05 1:37 Prednisone

where to buy prednisone in australia https://prednisonepills.pro/# - prednisone 200 mg tablets

# male erection pills https://edpill.pro/# - cheapest ed pills 2023/06/27 16:03 EdPills

male erection pills https://edpill.pro/# - cheapest ed pills

# buy ed pills https://edpillsotc.store/# - best ed pills at gnc 2023/10/08 2:51 EdPills

buy ed pills https://edpillsotc.store/# - best ed pills at gnc

# paxlovid covid https://paxlovid.bid/ paxlovid buy 2023/10/26 0:37 Paxlovid

paxlovid covid https://paxlovid.bid/ paxlovid buy

# prednisone without prescription medication https://prednisonepharm.store/ prednisone price australia 2024/01/20 18:05 Prednisone

prednisone without prescription medication https://prednisonepharm.store/ prednisone price australia

# gates of olympus demo türkçe - https://gatesofolympus.auction/ gates of olympus sırları 2024/03/27 21:12 Olympic

gates of olympus demo türkçe - https://gatesofolympus.auction/ gates of olympus sırları

タイトル
名前
URL
コメント