java常用工具类 UUID、Map工具类
本文实例为大家分享了Java常用工具类的具体代码,供大家参考,具体内容如下
UUID工具类
packagecom.jarvis.base.util; importjava.security.MessageDigest; importjava.security.NoSuchAlgorithmException; importjava.security.SecureRandom; /** *Aclassthatrepresentsanimmutableuniversallyuniqueidentifier(UUID). *AUUIDrepresentsa128-bitvalue. * *Thereexistdifferentvariantsoftheseglobalidentifiers.Themethods *ofthisclassareformanipulatingtheLeach-Salzvariant,althoughthe *constructorsallowthecreationofanyvariantofUUID(describedbelow). *
*Thelayoutofavariant2(Leach-Salz)UUIDisasfollows: *
*Themostsignificantlongconsistsofthefollowingunsignedfields: **0xFFFFFFFF00000000time_low *0x00000000FFFF0000time_mid *0x000000000000F000version *0x0000000000000FFFtime_hi **Theleastsignificantlongconsistsofthefollowingunsignedfields: **0xC000000000000000variant *0x3FFF000000000000clock_seq *0x0000FFFFFFFFFFFFnode ** *Thevariantfieldcontainsavaluewhichidentifiesthelayoutof *theUUID.Thebitlayoutdescribedaboveisvalidonlyfor *aUUIDwithavariantvalueof2,whichindicatesthe *Leach-Salzvariant. *
*Theversionfieldholdsavaluethatdescribesthetypeofthis *UUID.TherearefourdifferentbasictypesofUUIDs:time-based, *DCEsecurity,name-based,andrandomlygeneratedUUIDs.Thesetypes *haveaversionvalueof1,2,3and4,respectively. *
*FormoreinformationincludingalgorithmsusedtocreateUUIDs, *seetheInternet-Draft
UUIDsandGUIDs *orthestandardsbodydefinitionat * ISO/IEC11578:1996. * *@version1.14,07/12/04 *@since1.5 */ @Deprecated publicfinalclassUUIDimplementsjava.io.Serializable { /** *ExplicitserialVersionUIDforinteroperability. */ privatestaticfinallongserialVersionUID=-4856846361193249489L; /* *Themostsignificant64bitsofthisUUID. * *@serial */ privatefinallongmostSigBits; /** *Theleastsignificant64bitsofthisUUID. * *@serial */ privatefinallongleastSigBits; /* *TheversionnumberassociatedwiththisUUID.Computedondemand. */ privatetransientintversion=-1; /* *ThevariantnumberassociatedwiththisUUID.Computedondemand. */ privatetransientintvariant=-1; /* *ThetimestampassociatedwiththisUUID.Computedondemand. */ privatetransientvolatilelongtimestamp=-1; /* *TheclocksequenceassociatedwiththisUUID.Computedondemand. */ privatetransientintsequence=-1; /* *ThenodenumberassociatedwiththisUUID.Computedondemand. */ privatetransientlongnode=-1; /* *ThehashcodeofthisUUID.Computedondemand. */ privatetransientinthashCode=-1; /* *Therandomnumbergeneratorusedbythisclasstocreaterandom *basedUUIDs. */ privatestaticvolatileSecureRandomnumberGenerator=null; //ConstructorsandFactories /* *PrivateconstructorwhichusesabytearraytoconstructthenewUUID. */ privateUUID(byte[]data) { longmsb=0; longlsb=0; for(inti=0;i<8;i++) msb=(msb<<8)|(data[i]&0xff); for(inti=8;i<16;i++) lsb=(lsb<<8)|(data[i]&0xff); this.mostSigBits=msb; this.leastSigBits=lsb; } /** *ConstructsanewUUIDusingthespecifieddata. *mostSigBitsisusedforthemostsignificant64bits *oftheUUIDandleastSigBitsbecomesthe *leastsignificant64bitsoftheUUID. * *@parammostSigBits *@paramleastSigBits */ publicUUID(longmostSigBits,longleastSigBits) { this.mostSigBits=mostSigBits; this.leastSigBits=leastSigBits; } /** *Staticfactorytoretrieveatype4(pseudorandomlygenerated)UUID. * *The UUID
isgeneratedusingacryptographicallystrong *pseudorandomnumbergenerator. * *@returnarandomlygeneratedUUID. */ @SuppressWarnings("unused") publicstaticUUIDrandomUUID() { SecureRandomng=numberGenerator; if(ng==null) { numberGenerator=ng=newSecureRandom(); } byte[]randomBytes=newbyte[16]; ng.nextBytes(randomBytes); randomBytes[6]&=0x0f;/*clearversion*/ randomBytes[6]|=0x40;/*settoversion4*/ randomBytes[8]&=0x3f;/*clearvariant*/ randomBytes[8]|=0x80;/*settoIETFvariant*/ UUIDresult=newUUID(randomBytes); returnnewUUID(randomBytes); } /** *Staticfactorytoretrieveatype3(namebased)UUIDbasedon *thespecifiedbytearray. * *@paramnameabytearraytobeusedtoconstructaUUID. *@returnaUUIDgeneratedfromthespecifiedarray. */ publicstaticUUIDnameUUIDFromBytes(byte[]name) { MessageDigestmd; try { md=MessageDigest.getInstance("MD5"); } catch(NoSuchAlgorithmExceptionnsae) { thrownewInternalError("MD5notsupported"); } byte[]md5Bytes=md.digest(name); md5Bytes[6]&=0x0f;/*clearversion*/ md5Bytes[6]|=0x30;/*settoversion3*/ md5Bytes[8]&=0x3f;/*clearvariant*/ md5Bytes[8]|=0x80;/*settoIETFvariant*/ returnnewUUID(md5Bytes); } /** *CreatesaUUIDfromthestringstandardrepresentationas *describedinthe{@link#toString}method. * *@paramnameastringthatspecifiesaUUID. *@returnaUUIDwiththespecifiedvalue. *@throwsIllegalArgumentExceptionifnamedoesnotconformtothe *stringrepresentationasdescribedin{@link#toString}. */ publicstaticUUIDfromString(Stringname) { String[]components=name.split("-"); if(components.length!=5) thrownewIllegalArgumentException("InvalidUUIDstring:"+name); for(inti=0;i<5;i++) components[i]="0x"+components[i]; longmostSigBits=Long.decode(components[0]).longValue(); mostSigBits<<=16; mostSigBits|=Long.decode(components[1]).longValue(); mostSigBits<<=16; mostSigBits|=Long.decode(components[2]).longValue(); longleastSigBits=Long.decode(components[3]).longValue(); leastSigBits<<=48; leastSigBits|=Long.decode(components[4]).longValue(); returnnewUUID(mostSigBits,leastSigBits); } //FieldAccessorMethods /** *Returnstheleastsignificant64bitsofthisUUID's128bitvalue. * *@returntheleastsignificant64bitsofthisUUID's128bitvalue. */ publiclonggetLeastSignificantBits() { returnleastSigBits; } /** *Returnsthemostsignificant64bitsofthisUUID's128bitvalue. * *@returnthemostsignificant64bitsofthisUUID's128bitvalue. */ publiclonggetMostSignificantBits() { returnmostSigBits; } /** *TheversionnumberassociatedwiththisUUID.Theversion *numberdescribeshowthisUUIDwasgenerated. * *Theversionnumberhasthefollowingmeaning:*
*
* *@returntheversionnumberofthisUUID. */ publicintversion() { if(version<0) { //Versionisbitsmaskedby0x000000000000F000inMSlong version=(int)((mostSigBits>>12)&0x0f); } returnversion; } /** *ThevariantnumberassociatedwiththisUUID.Thevariant *numberdescribesthelayoutoftheUUID. * *Thevariantnumberhasthefollowingmeaning:- 1Time-basedUUID *
- 2DCEsecurityUUID *
- 3Name-basedUUID *
- 4RandomlygeneratedUUID *
*
*
* *@returnthevariantnumberofthisUUID. */ publicintvariant() { if(variant<0) { //Thisfieldiscomposedofavaryingnumberofbits if((leastSigBits>>>63)==0) { variant=0; } elseif((leastSigBits>>>62)==2) { variant=2; } else { variant=(int)(leastSigBits>>>61); } } returnvariant; } /** *ThetimestampvalueassociatedwiththisUUID. * *- 0ReservedforNCSbackwardcompatibility *
- 2TheLeach-Salzvariant(usedbythisclass) *
- 6Reserved,MicrosoftCorporationbackwardcompatibility *
- 7Reservedforfuturedefinition *
The60bittimestampvalueisconstructedfromthetime_low, *time_mid,andtime_hifieldsofthisUUID.Theresulting *timestampismeasuredin100-nanosecondunitssincemidnight, *October15,1582UTC.
*
*Thetimestampvalueisonlymeaningfulinatime-basedUUID,which *hasversiontype1.IfthisUUIDisnotatime-basedUUIDthen *thismethodthrowsUnsupportedOperationException. * *@throwsUnsupportedOperationExceptionifthisUUIDisnota *version1UUID. */ publiclongtimestamp() { if(version()!=1) { thrownewUnsupportedOperationException("Notatime-basedUUID"); } longresult=timestamp; if(result<0) { result=(mostSigBits&0x0000000000000FFFL)<<48; result|=((mostSigBits>>16)&0xFFFFL)<<32; result|=mostSigBits>>>32; timestamp=result; } returnresult; } /** *TheclocksequencevalueassociatedwiththisUUID. * *The14bitclocksequencevalueisconstructedfromtheclock *sequencefieldofthisUUID.Theclocksequencefieldisusedto *guaranteetemporaluniquenessinatime-basedUUID.
*
*TheclockSequencevalueisonlymeaningfulinatime-basedUUID,which *hasversiontype1.IfthisUUIDisnotatime-basedUUIDthen *thismethodthrowsUnsupportedOperationException. * *@returntheclocksequenceofthisUUID. *@throwsUnsupportedOperationExceptionifthisUUIDisnota *version1UUID. */ publicintclockSequence() { if(version()!=1) { thrownewUnsupportedOperationException("Notatime-basedUUID"); } if(sequence<0) { sequence=(int)((leastSigBits&0x3FFF000000000000L)>>>48); } returnsequence; } /** *ThenodevalueassociatedwiththisUUID. * *The48bitnodevalueisconstructedfromthenodefieldof *thisUUID.ThisfieldisintendedtoholdtheIEEE802address *ofthemachinethatgeneratedthisUUIDtoguaranteespatial *uniqueness.
*
*Thenodevalueisonlymeaningfulinatime-basedUUID,which *hasversiontype1.IfthisUUIDisnotatime-basedUUIDthen *thismethodthrowsUnsupportedOperationException. * *@returnthenodevalueofthisUUID. *@throwsUnsupportedOperationExceptionifthisUUIDisnota *version1UUID. */ publiclongnode() { if(version()!=1) { thrownewUnsupportedOperationException("Notatime-basedUUID"); } if(node<0) { node=leastSigBits&0x0000FFFFFFFFFFFFL; } returnnode; } //ObjectInheritedMethods /** *ReturnsaString
objectrepresentingthis *UUID
. * *TheUUIDstringrepresentationisasdescribedbythisBNF: *
*UUID=* *@returnastringrepresentationofthisUUID. */ publicStringtoString() { return(digits(mostSigBits>>32,8)+"-"+ digits(mostSigBits>>16,4)+"-"+ digits(mostSigBits,4)+"-"+ digits(leastSigBits>>48,4)+"-"+ digits(leastSigBits,12)); } /** *Returnsvalrepresentedbythespecifiednumberofhexdigits. */ privatestaticStringdigits(longval,intdigits) { longhi=1L<<(digits*4); returnLong.toHexString(hi|(val&(hi-1))).substring(1); } /** *Returnsahashcodeforthis"-" "-" * "-" * "-" * *time_low=4* *time_mid=2* *time_high_and_version=2* *variant_and_sequence=2* *node=6* *hexOctet= *hexDigit= *"0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9" *|"a"|"b"|"c"|"d"|"e"|"f" *|"A"|"B"|"C"|"D"|"E"|"F" * UUID
. * *@returnahashcodevalueforthisUUID. */ publicinthashCode() { if(hashCode==-1) { hashCode=(int)((mostSigBits>>32)^ mostSigBits^ (leastSigBits>>32)^ leastSigBits); } returnhashCode; } /** *Comparesthisobjecttothespecifiedobject.Theresultis *trueifandonlyiftheargumentisnot *null,isaUUIDobject,hasthesamevariant, *andcontainsthesamevalue,bitforbit,asthisUUID. * *@paramobjtheobjecttocomparewith. *@returntrue
iftheobjectsarethesame; *false
otherwise. */ publicbooleanequals(Objectobj) { if(!(objinstanceofUUID)) returnfalse; if(((UUID)obj).variant()!=this.variant()) returnfalse; UUIDid=(UUID)obj; return(mostSigBits==id.mostSigBits&& leastSigBits==id.leastSigBits); } //ComparisonOperations /** *ComparesthisUUIDwiththespecifiedUUID. * *ThefirstoftwoUUIDsfollowsthesecondifthemostsignificant *fieldinwhichtheUUIDsdifferisgreaterforthefirstUUID. * *@paramvalUUIDtowhichthisUUIDistobecompared. *@return-1,0or1asthisUUIDislessthan,equal *to,orgreaterthanval. */ publicintcompareTo(UUIDval) { //TheorderingisintentionallysetupsothattheUUIDs //cansimplybenumericallycomparedastwonumbers return(this.mostSigBits
val.mostSigBits?1: (this.leastSigBits val.leastSigBits?1: 0)))); } /** *ReconstitutetheUUIDinstancefromastream(thatis, *deserializeit).Thisisnecessarytosetthetransientfields *totheircorrectuninitializedvaluesotheywillberecomputed *ondemand. */ privatevoidreadObject(java.io.ObjectInputStreamin) throwsjava.io.IOException,ClassNotFoundException { in.defaultReadObject(); //Set"cachedcomputation"fieldstotheirinitialvalues version=-1; variant=-1; timestamp=-1; sequence=-1; node=-1; hashCode=-1; } }
Map工具类
packagecom.jarvis.base.util; importjava.util.Map; /** * * *@Title:MapHelper.java *@Packagecom.jarvis.base.util *@Description:Map工具类 *@versionV1.0 */ publicclassMapHelper{ /** *获得字串值 * *@paramname *键值名称 *@return若不存在,则返回空字串 */ publicstaticStringgetString(Map,?>map,Stringname){ if(name==null||name.equals("")){ return""; } Stringvalue=""; if(map.containsKey(name)==false){ return""; } Objectobj=map.get(name); if(obj!=null){ value=obj.toString(); } obj=null; returnvalue; } /** *返回整型值 * *@paramname *键值名称 *@return若不存在,或转换失败,则返回0 */ publicstaticintgetInt(Map,?>map,Stringname){ if(name==null||name.equals("")){ return0; } intvalue=0; if(map.containsKey(name)==false){ return0; } Objectobj=map.get(name); if(obj==null){ return0; } if(!(objinstanceofInteger)){ try{ value=Integer.parseInt(obj.toString()); }catch(Exceptionex){ ex.printStackTrace(); System.err.println("name["+name+"]对应的值不是数字,返回0"); value=0; } }else{ value=((Integer)obj).intValue(); obj=null; } returnvalue; } /** *获取长整型值 * *@paramname *键值名称 *@return若不存在,或转换失败,则返回0 */ publicstaticlonggetLong(Map,?>map,Stringname){ if(name==null||name.equals("")){ return0; } longvalue=0; if(map.containsKey(name)==false){ return0; } Objectobj=map.get(name); if(obj==null){ return0; } if(!(objinstanceofLong)){ try{ value=Long.parseLong(obj.toString()); }catch(Exceptionex){ ex.printStackTrace(); System.err.println("name["+name+"]对应的值不是数字,返回0"); value=0; } }else{ value=((Long)obj).longValue(); obj=null; } returnvalue; } /** *获取Float型值 * *@paramname *键值名称 *@return若不存在,或转换失败,则返回0 */ publicstaticfloatgetFloat(Map,?>map,Stringname){ if(name==null||name.equals("")){ return0; } floatvalue=0; if(map.containsKey(name)==false){ return0; } Objectobj=map.get(name); if(obj==null){ return0; } if(!(objinstanceofFloat)){ try{ value=Float.parseFloat(obj.toString()); }catch(Exceptionex){ ex.printStackTrace(); System.err.println("name["+name+"]对应的值不是数字,返回0"); value=0; } }else{ value=((Float)obj).floatValue(); obj=null; } returnvalue; } /** *获取Double型值 * *@paramname *键值名称 *@return若不存在,或转换失败,则返回0 */ publicstaticdoublegetDouble(Map,?>map,Stringname){ if(name==null||name.equals("")){ return0; } doublevalue=0; if(map.containsKey(name)==false){ return0; } Objectobj=map.get(name); if(obj==null){ return0; } if(!(objinstanceofDouble)){ try{ value=Double.parseDouble(obj.toString()); }catch(Exceptionex){ ex.printStackTrace(); System.err.println("name["+name+"]对应的值不是数字,返回0"); value=0; } }else{ value=((Double)obj).doubleValue(); obj=null; } returnvalue; } /** *获取Bool值 * *@paramname *键值名称 *@return若不存在,或转换失败,则返回false */ publicstaticbooleangetBoolean(Map,?>map,Stringname){ if(name==null||name.equals("")){ returnfalse; } booleanvalue=false; if(map.containsKey(name)==false){ returnfalse; } Objectobj=map.get(name); if(obj==null){ returnfalse; } if(objinstanceofBoolean){ return((Boolean)obj).booleanValue(); } value=Boolean.valueOf(obj.toString()).booleanValue(); obj=null; returnvalue; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。