七つの武器:apache commons:commons-lang

5999 ワード

前言
ある人はapacheが乞食だと言っていますが、いろいろなオープンソースプロジェクトが混ざっていて、差がありません.
今日はcommonsバッグを整理してみましたが、まずはcommons-lang.
一目見た後、1つの字:雑で、スイスの軍刀のようで、用途が多くて雑です.
 
どのようにorganizeこの種類のJDK utilコードか?
1) the most interesting in design or implementation
2) the most useful 
3) see how other developer uses, wrap, rewrite JDK
本文
lang.builder.*
次の4つのmethodsを実現する際に、1つのclassにfieldsがたくさんある場合は、煩雑でboring的な仕事になります.
  • equals
  • toString
  • hashCode
  • compareTo

  • example code
    public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MyClass rhs = (MyClass) obj; return new EqualsBuilder() .appendSuper(super.equals(obj)) .append(field1, rhs.field1) .append(field2, rhs.field2) .append(field3, rhs.field3) .isEquals(); } 
     
    public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } 
    lang.reflect.*
    MethodUtils
     
    getMatchingAccessibleMethod

    Find an accessible method that matches the given name and has compatible parameters. Compatible parameters mean that every method parameter is assignable from the given parameters. In other words, it finds a method with the given name that will take the parameters given.
     
    This method can match primitive parameter by passing in wrapper classes. For example, a  Boolean  will match a primitive  boolean  parameter.
     
    invokeMethodでisAssignableFromを使用すると、実装コードは次のようになります.
    Method bestMatch = null; Method[] methods = cls.getMethods(); for (int i = 0, size = methods.length; i < size; i++) { if (methods[i].getName().equals(methodName)) {//compare parameters if (ClassUtils.isAssignable(parameterTypes, methods[i] .getParameterTypes(), true)) {//get accessible version of method Method accessibleMethod = getAccessibleMethod(methods[i]); if (accessibleMethod != null) { if (bestMatch == null || MemberUtils.compareParameterTypes( accessibleMethod.getParameterTypes(), bestMatch.getParameterTypes(), parameterTypes) < 0) { bestMatch = accessibleMethod; } } } } } 
     
    getAccessibleMethod
     
    Return an accessible method (that is, one that can be invoked via reflection) with given name and parameters. If no such method can be found, return  null .
    invokeExactMethodでは、主な実装コードは以下の通りであり、getDeclaredMethodとgetSuperclassが再帰的に実装される.
    //Search up the superclass chain for (; cls != null; cls = cls.getSuperclass()) {//Check the implemented interfaces of the parent class Class[] interfaces = cls.getInterfaces(); for (int i = 0; i < interfaces.length; i++) {//Is this interface public? if (!Modifier.isPublic(interfaces[i].getModifiers())) { continue; }//Does the method exist on this interface? try { method = interfaces[i].getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) {/* * Swallow, if no method is found after the loop then this * method returns null. */} if (method != null) { break; }//Recursively check our parent interfaces method = getAccessibleMethodFromInterfaceNest(interfaces[i], methodName, parameterTypes); if (method != null) { break; } } } 
    invokeExactMethod
    Invoke a static method whose parameter types match exactly the parameter types given.
    この方法とinvokeMethodの違いは次の例を参照してください.
    invokeExactStaticMethod
      Invoke a named static method whose parameter type matches the object type.
    静的メソッドinvokeの場合、最初のobjectパラメータがnullに入力されるとmethod.invoke(null, args);
     
    getMethodsは、継承された親クラスと実装されたインタフェースのメソッドを含むすべてのpublicのmember methodsを返します.従って,静的手法も含まれる.
    invokeMethod
     
     Invoke a named method whose parameter type matches the object type.
    public class Parent { } public class Child extends Parent { }//--------------------------------------------------//Can pass both Child, Parent//Parent.class.isAssignableFrom(parameter.class) public class Main { public void pass(Parent parameter) {//... } }//-------------------------------------------------- Main main = new Main(); Child child = new Child(); MethodUtils.invokeMethod(main, "pass", child);//OK MethodUtils.invokeExactMethod(child, "pass', child);//exception, java.lang.NoSuchMethodException: No such accessible method: pass() on object: org.leef.Child  
    lang.time.*
    FastDateFormat
    SimpleDateFormat is not thread-safe in any JDK version, nor will it be as Sun have closed the bug/RFE.
    why SimpleDateFormat         ?    field mutable

    解決策はたくさんありますが、
    毎回newにsynchronizeを加えてthread-localを使用し、毎回newと差が少ない.スレッドが再利用されると、object-poolを使用して複数のオブジェクトを共有するnewの回数が減少します.
    StopWatch
    lang.text.*
    StrSubstitutor 
    プレースホルダの置換
    Map valuesMap = HashMap(); valuesMap.put("animal", "quick brown fox"); valuesMap.put("target", "lazy dog"); String templateString = "The ${animal} jumped over the ${target}."; StrSubstitutor sub = new StrSubstitutor(valuesMap); String resolvedString = sub.replace(templateString) 
    StrTokenizer(guavaのsplitterに対応)
    StrMatcher(guavaのCharMatcherに対応)
    StrBuilder(guavaのJoinerに対応)
    lang.*
    WordUtils
    capitalize用
     
    StringUtils
    Joinもsplitも
     
    ArrayUtils
    nullToEmpty:Defensive programming technique、null配列をempty(sizeが0)の配列に変換します.
    add/remove:配列要素の追加または削除
    lang.math.* lang.exception.*
    JVMRandom:ShardSeedRandom、Randomより速い??
    RandomUtils
    リファレンス
    http://www.slideshare.net/tcurdt/apache-commons-dont-reinvent-the-wheel-presentation
     
    http://commons.apache.org/lang/userguide.html