common java java n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
COMMON JAVA JAVA 数据结构与常用类库简介 PowerPoint Presentation
Download Presentation
COMMON JAVA JAVA 数据结构与常用类库简介

Loading in 2 Seconds...

play fullscreen
1 / 169

COMMON JAVA JAVA 数据结构与常用类库简介 - PowerPoint PPT Presentation


  • 655 Views
  • Uploaded on

COMMON JAVA JAVA 数据结构与常用类库简介. Bingoo. JAVA 类加载. Java Classloading. Why do we care? Because if we’re gonna write code at runtime, we’d better know how to load and use it… Because we don’t really understand classes So… what identifies a class? Its name Its package Its classloader

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'COMMON JAVA JAVA 数据结构与常用类库简介' - rafi


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
java classloading
Java Classloading
  • Why do we care?
    • Because if we’re gonna write code at runtime, we’d better know how to load and use it…
    • Because we don’t really understand classes
  • So… what identifies a class?
    • Its name
    • Its package
    • Its classloader
  • It means that
    • We can have multiple instances of a class loaded at the same time
    • Two instances of the same class from different classloaders are not compatible and not assignable
    • Static variables are static only in the context of a classloader, not globally as we’re always told
slide4

Java Classloading

  • So what is this classloader?
    • A Java class (subclass of java.lang.ClassLoader),

responsible for loading other classes used by the JVM

    • Classloaders are arranged as a tree
  • Bootstrap classloader
    • Loads the Java system
      • jre/lib/resources.jar – series of resource files
      • jre/lib/rt.jar – the java.*, javax.*, etc packages
      • jre/lib/sunrsasign.jar
      • jre/lib/jsse.jar – secure socket extension
      • jre/lib/jce.jar – Java cryptography extension
      • jre/lib/charsets.jar
      • jre/classes
    • The important stuff is in rt.jar – the base Java classes
slide5

Java Classloading

Commandline Java App

Tomcat (6)

Bootstrap classloader

Loads onlybootstrap.jar and tomcat-juli.jar

Ext classloader

Application/ System classloader

Loads Tomcat commons library jars

Loads the Application Jars from the classpath

Application/ System classloader

Common classloader

Loads jars in the webapp lib directory

WAR 1

classloader

WAR 2

classloader

classnotfoundexception and noclassdeffounderror
ClassNotFoundException and NoClassDefFoundError
  • ClassNotFoundExceptioncomes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws ClassNotFoundException
  • While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason. 
slide8

aopalliance-1.0.jar

asm-3.3.jar

asm-commons-3.3.jar

asm-tree-3.3.jar

axis-1.4.jar

bcprov-jdk16-1.45.jar

cglib-nodep-2.2.jar

commons-beanutils-1.8.3.jar

commons-codec-1.5.jar

commons-collections-3.2.jar

commons-discovery-0.4.jar

commons-fileupload-1.2.2.jar

commons-httpclient-3.1.jar

commons-io-2.0.1.jar

commons-lang-2.1.jar

commons-logging-1.1.1.jar

commons-net-2.2.jar

commons-pool-1.6.jar

commons-ssh-1.5.1.jar

dom4j-1.6.1.jar

ems-consumer-0.0.1-SNAPSHOT.jar

fastjson-1.1.17.jar

freemarker-2.3.18.jar

guava-12.0.jar

hadoop-core-0.20-append-r1056497.jar

hbase-0.90.4.jar

hessian-3.1.6.jar

ibatis-sqlmap-2.3.4.726.M01.jar

javassist-3.11.0.GA.jar

jline-0.9.94.jar

jmockit-0.999.4.jar

jsch-0.1.46.jar

jsr305-1.3.9.jar

junit-4.8.2.jar

kafka-0.7.0.jar

Linkage-EcsCommon-0.0.1.jar

log4j-1.2.16.jar

ntfPlat-mailsend-0.0.1.jar

ntfplat-send-0.0.1.jar

ognl-3.0.4.jar

PageSecurity-0.0.2.jar

phw-all-0.1.0.jar

ProxyForEcsSms-1.0.jar

scala-library-2.8.0.jar

slf4j-api-1.6.2.jar

slf4j-log4j12-1.6.2.jar

solr-solrj-3.4.0.jar

spring-2.5.6.jar

spring-beans-2.5.6.jar

spring-context-2.5.6.jar

spring-context-support-2.5.6.jar

spring-core-2.5.6.jar

spring-web-2.5.6.jar

spring-webmvc-2.5.6.jar

spymemcached-2.8.0.jar

struts2-convention-plugin-2.3.1.2.jar

struts2-core-2.3.1.2.jar

struts2-json-plugin-2.3.1.2.jar

wsdl4j-1.6.2.jar

xerces-2.6.2.jar

xwork-core-2.3.1.2.jar

zkclient-0.1.jar

zookeeper-3.3.3.jar

best practises for designing the api
几种设计异常的最佳实践 (Best Practises for Designing the API)
  • 选择Checked还是Unchecked的几个经典依据
  • Exception的封装问题
  • 如无必要不要创建自己的Exception
  • 不要用Exception来作流程控制
  • 不要轻易的忽略捕获的Exception
  • 不要简单地捕获顶层的Exception
slide12
三种”情景”导致异常的抛出
  • 编程错误导致(Exception due Programming errors)
    • 这种情景下,异常往往处于编程错误(如:NullPointerException或者 IllegalArgumentException),这时异常一旦抛出,客户端将变得无能为力。
  • 客户端代码错误导致(Exception due client code errors)
    • 客户端试图调用API不允许的操作
  • 资源失败导致(Exception due to resource failures)
    • 如内存不足或网络连接失败导致出现异常等。这些异常的出现客户端可以采取相应的措施来恢复应用程序的继续运行。
slide13

Java中异常的类型 Checked and Unchecked Exceptions

  • A checked exception is one that will be checked by the compiler for a surrounding try/catch block if that method have a throws clause
  • An unchecked exception, also called a RuntimeException, does not require programmer intervention with a try/catch block
    • Either there is nothing we can do with this type of problem (sun)
    • Or, this type of problem can be remedied by fixing code
      • For example, an ArrayIndexOutOfBounds
checked or unchecked exception
Checked or Unchecked exception
  • 问自己一个问题,“如果这种异常一旦抛出,客户端会做怎样的补救?”
    • 如果客户端可以通过其他的方法恢复异常,那么这种异常就是checked exception;
    • 如果客户端对出现的这种异常无能为力,那么这种异常就是Unchecked exception;
    • 尽量使用unchecked exception来处理编程错误;譬如:NullPointerException , IllegalArgumentException和 IllegalStateException
preserve encapsulation
 保护封装性(Preserve encapsulation)
  • 不要让你要抛出的checked exception升级到较高的层次。
    • 例如,不要让SQLException延伸到业务层。业务层并不需要(不关心?)SQLException。
    • 转变SQLException为另外一个checked exception,如果客户端并不需要恢复这种异常的话;
    • 转变SQLException为一个unchecked exception,如果客户端对这种异常无能为力的话(多数情况);
slide16
使用异常最佳实践
  • 总是要做一些清理工作(Always clean up after yourself)
    • 如果使用一些资源例如数据库连接或者网络连接,请记住要做一些清理工作(如关闭数据库连接或者网络连接)
    • 要用try-finally来做必要的清理工作
  • 不要使用异常来控制流程(Never use exceptions for flow control)
  • 不要忽略异常
    • 当有异常被抛出的时候,如果你不想恢复它,那么你要毫不犹豫的将其转换为unchecked exception,而不是用一个空的catch块或者什么也不做来忽略它,以至于从表面来看象是什么也没有发生一样。
  • 不要捕获顶层的Exception
    • unchecked exception都是RuntimeException的子类,RuntimeException又继承Exception,因此,如果单纯的捕获Exception,那么你同样也捕获了RuntimeException,它将忽略所有的异常,包括unchecked exception.
  •  Log exceptions just once
    • Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the original source of exception. So just log it once.
guava throwables
Guava Throwables

try{someMethodThatCouldThrowAnything();}catch(IKnowWhatToDoWithThisException e){handle(e);}catch(Throwable t){Throwables.propagateIfInstanceOf(t,IOException.class);Throwables.propagateIfInstanceOf(t,SQLException.class);throwThrowables.propagate(t);}

slide20

Annotation Definition

  • Structured Data
    • Comparable to records in OCaml

@interfaceMyAnnotation {

String value(); // member

int i() default 123; // member w. default value

}

@interfaceMarkerAnnotation {

// annotation without any members

}

slide21

Annotation Usage

@MyAnnotation(value="text", i=456)

void method() { … }

// default value for i: 123

@MyAnnotation(value="text")

void method2() { … }

// special case for members called "value"

@MyAnnotation("text")

void method3() { … }

// parenthesis can be omitted if no members

@MarkerAnnotation

void method4() { … }

slide22

Annotation Members

@interface MyAnnotation {

intintMember();// primitives

StringstringMember();// strings

ClassclassMember(); // class literals

SomeEnumenumMember();// enums

// annotions

OnlyThreadWithName annotMember();

// arrays of the above

OnlyThreadWithName[]arrayMember();

}

slide23

Annotation Targets in Java 5

@Apackage some.package.name;

@BclassMyClass {

@CObject field;

@DMyClass(@EObject param) {

field = param;

}

@FObject method() {

@GObject localVar = field;

return localVar;

}

}

slide24

The Target annotation

@Target(ElementType.TYPE)

—can be applied to any element of a class

@Target(ElementType.FIELD)

—can be applied to a field or property

@Target(ElementType.METHOD)

—can be applied to a method level annotation

@Target(ElementType.PARAMETER)

—can be applied to the parameters of a method

@Target(ElementType.CONSTRUCTOR)

—can be applied to constructors

@Target(ElementType.LOCAL_VARIABLE)

—can be applied to local variables

@Target(ElementType.ANNOTATION_TYPE)

—indicates that the declared type itself is an

slide25

告知程序如何处理@Retention

java.lang.reflect.AnnotatedElement接口

public Annotation getAnnotation(Class annotationType);

public Annotation[] getAnnotations();

public Annotation[] getDeclaredAnnotations();

public boolean isAnnotationPresent(Class annotationType);

Class、Constructor、Field、Method、Package等类别,都实现了AnnotatedElement接口

logging use cases
 Logging use-cases
  • debugging the software during development
  • help diagnose bugs during production
  • trace access for security purposes
  • create data for statistical use
  • etc
history
History
  • System.out.println()
  • System.err.println()
  • e.printStackTrace() 
components
Components

Level/ Priority

Aplicaction

Logger

1..*

Appender

Filter

Layout

slide30

LoggerNamedHierarchy

Aloggerissaidtobeanancestorofanotherloggerif itsnamefollowedbyadotistheprefixpartinthe

descendantloggername.

PS: 大小写敏感

root

com.site.software

com.site.software.model

com.site.software.model.dao

com.site.software.model.dao.PersonDAOImpl

com.site.software.view

com.site.softwareisanancestorloggerofthedescendant

com.site.software.model.dao

●com.site.softwareistheparentloggerofthechild

com.site.software.model

slide31

Levels

Aloggermaybeassignedtoalevel.

Propertiesconfigurationfile

log4j.rootLogger=ERROR

log4j.logger.com.site.software=INFO

XMLconfigurationfile

Javaconfigurationfile

Logger.getRootLogger().setLevel(Level.ERROR);

Logger.getLogger(“com.site.software”).setLevel(Level.INFO);

levelsareordered

TRACE<DEBUG<INFO<WARN<ERROR<FATAL

level priority
Level/ Priority
  • FATAL:Displays messages of situations that probably will abort the application.
  • ERROR:Displays error messages that are unwanted but not interrupt the application.
  • WARN:Displays messages from dangerous regions for the application, or certain operations use not recommended.
  • INFO:Displays information messages about the execution of the application, or important events.
  • DEBUG: Shows debug messages for the application. (Used in development time)
  • ALL: Show all posts
  • OFF:Disables all messages.
slide33

LevelInheritance

TheinheritedlevelforagivenloggerL,isequalto

thefirstnon-nulllevelinthelogger named hierarchy,

startingatLandproceedingupwardsinthe

hierarchytowardstherootlogger.

AssignedInherited

Levellevel

LoggerName

root

com.site.software

com.site.software.model

com.site.software.model.dao

com.site.software.model.dao.PersonDAOImpl

com.site.software.view

ERROR

WARN

INFO

null

null

null

ERROR

WARN

INFO

INFO

INFO

WARN

slide36

LoggingRequest

Alogrequestoflevelpinaloggerconfigured(either

assignedorinherited,whicheverisappropriate)with

levelq,isenabledifp>=q.

importorg.apache.log4j.Logger;

publicclassPersonDAOImpl{

privatefinalLoggerLOG=Logger.getLogger(PersonDAOImpl.class);

publicPersonDAOImpl(){

LOG.debug("Youcan'tseemeinthelogbecausedebug<INFO");

LOG.info("Youwillseemeinthelogbecauseinfo=INFO");

LOG.warn("Youwillseemeinthelogbecausewarn>INFO");

slide37

Appenders

Aloggermaybeassignedtoanappender:anamed

outputdestinationyourlogmessagesareforwarded

to.

#Therootloggerlogstotheconsole

log4j.rootLogger=ERROR,con

#Thecom.site.softwareloggerlogstoafile

log4j.logger.com.site.software=INFO,FileApp

#Theconappenderwilllogintheconsole

log4j.appender.con=org.apache.log4j.ConsoleAppender

#TheFileAppappenderwillloginafile

log4j.appender.FileApp=org.apache.log4j.FileAppender

slide39

AppenderAdditivity

EachenabledloggingrequestforagivenloggerL

willbeforwardedtoalltheappendersinthatlogger

LAaswellasalltheappendershigherHAinthe

logger named hierarchy.

LoggerName

root

com.site.software

com.site.software.model

com.site.software.model.dao

com.site.software.view

LA

con

null

FileApp,c

d

e

HA

con

con

FileApp,c,con

con

slide41

LayoutConversionPattern

Eachappenderhasalayoutcomponentresponsible

forformattinglogmessagesaccordinglyto

conversionpatterns.

log4j.appender.con=org.apache.log4j.ConsoleAppender

log4j.appender.con.layout=org.apache.log4j.PatternLayout

log4j.appender.con.layout.ConversionPattern=%d[%t]%-5p%m(%c:%L)%n

Producedlogs:

2010-05-1419:29:11,996[main]INFOYouwillseemeinthelogbecause

info=INFO(com.site.software.model.dao.PersonDAOImpl:10)

2010-05-1419:29:11,997[main]WARNYouwillseemeinthelogbecause

warn>INFO(com.site.software.model.dao.PersonDAOImpl:11)

slide42

AlotofAppendersandLayouts

Appenders

●ConsoleAppenderappendslogeventstoSystem.outorSystem.err

●FileAppenderappendslogeventstoafile

●RollingFileAppenderextendsFileAppendertobackupthelogfileswhen

theyreachacertainsize

●DailyRollingFileAppenderextendsFileAppendersothattheunderlyingfile

isrolledoveratauserchosenfrequency

●SMTPAppendersendsane-mailwhenaspecificloggingeventoccurs

●JMSAppenderpublisheslogeventstoaJMSTopic

●JDBCAppenderprovidesforsendinglogeventstoadatabase

Layouts

●PatternLayoutconfigurablestringpatterninaprintfCfunctionstyle

●XMLLayoutappendslogeventsasaseriesoflog4j:event(log4j.dtd)

●HTMLLayoutoutputseventsinaHTMLtable

the api
The API

1: import org.slf4j.Logger;

2: import org.slf4j.LoggerFactory;

3:

4: public class Wombat {

5:

6: private final Logger logger = LoggerFactory.getLogger(Wombat.class);

7: Integer t;

8: Integer oldT;

9:

10: public void setTemperature(Integer temperature) {

11:

12: oldT = t;

13: t = temperature;

14:

15: logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);

16:

17: if(temperature.intValue() > 50) {

18: logger.info("Temperature has risen above 50 degrees.");

19: }

20: }

21: }

slf4j logback
SLF4J & Logback

logback的前世今生

  • slf4j由log4j作者Ceki开发,逐步取代apahce commons logging。
  • logback由log4j作者Ceki开发,逐步取代log4j。
logback log4j
logback相比较log4j的优势
  • slf4j支持参数化
    • logger.error(“帐号ID:{}不存在”, userId);
    • 告别了if(logger.isDebugEnable()) 时代
  • 另外logback的整体性能比log4j也较佳,hibernate等项目已经采用了slf4j。
slf4j and logback dream dates
SLF4J and Logback : Dream Dates!
  • Logback implements SLF4J natively
  • No computational and memory overhead
  • Fully compliant to SLF4J
  • Faster they say! 10 times!! Smaller Blue Print
  • Core, classic and access modules
why logback
Why Logback
  • Conditional Processing
    • Good For Dev/Prod switch

Is It Worth A Use?

why logback1
Why Logback
  • Stack Traces Pointing jar files
logback xml

ConsoleAppender

RollingFileAppender

rollover daily or whenever the

file size reaches 100MB

logback.xml
parameterized logging
Parameterized logging

inefficient syle

logger.debug("Hello "+name);

old style:

if(logger.isDebugEnabled()) {

logger.debug("Hello "+name);

}

new style:

logger.debug("Hello {}", name);

siftingappender or the appender making appender
SiftingAppender or the appender-making appender
  • Sift logging according to runtime attributes
  • E.g. separate logs according to user sessions, so that the log file generated by every user go into distinct log files, one log file per user.
  • Works with any appender, not just FileAppender
siftingappender continued
SiftingAppender (continued)

<appendername="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender">

<discriminator>

<Key>userid</Key>

<DefaultValue>unknown</DefaultValue>

</discriminator>

<sift>

<appendername="FILE-${userid}" 

class="ch.qos.logback.core.FileAppender">

<File>${userid}.log</File>s

<Append>false</Append>

<layout>

<Pattern>%d %level %mdc %logger - %msg%n</Pattern>

</layout>

</appender>

</sift>

</appender>

mapped diagnostic context mdc
Mapped Diagnostic Context(MDC)
  • 线程映射表
  • 日志框架维护的 map,日志框架通过提供了的键值对向其中插入日志信息。

映射诊断环境(Mapped Diagnostic Context)

Logback的设计目标之一是审查和调试复杂的分布式应用程序。真实世界的多数分布式系统需要同时处理多个客户端。在一个典型的多线程方式实现的分布式系统里,不同的线程处理不同的客户端。区分不同客户端的记录输出的一个可行的但不好的方法是为每个客户端都创建新的、独立的logger。这种技术使logger的数量增多且大大增加了管理开销。

一个轻量的技术是为客户端的每个记录请求添加唯一戳(uniquely stamp)Logback在SLJ4J里使用了这种技术的一种变体:映射诊断环境(MDC)

为了给每个请求添加唯一戳,用户把环境(context)信息放进MDContext)

slide56
MDC
  • MDC : Map Diagnostic Context
    • Helps to uniquely stamp requests
    • Similar to NDC : Nested Diagnostic Context
    • Correlating the logs effectively
  • The MDC manages contextual information on a per thread basis(and its children)

@Override

publicvoidprocessMsg(EmsMessageemsMessage) {

EopLogBeanmsg = (EopLogBean) emsMessage.getMsg();

MDC.put(“userid", getActionFromTxid(msg.getTrxid()));

log.info(msg.toString());

}

mdc use case user based logging
MDC Use Case: User Based Logging

public class UserServletFilter implements Filter {

private final String USER_KEY = "username";

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

HttpServletRequestreq = (HttpServletRequest) request;

Principal principal = req.getUserPrincipal();

if (principal != null) {

String username = principal.getName();

MDC.put(USER_KEY, username);

}

try {

chain.doFilter(request, response);

} finally {

MDC.remove(USER_KEY);

}

}

}

mdc use case user based logging1
MDC Use Case: User Based Logging

  <appender name="CONSOLE“ class="ch.qos.logback.core.ConsoleAppender">

    <layout class="ch.qos.logback.classic.PatternLayout">

      <Pattern>%-4r [%thread] %-5level C:%X{username} - %msg%n</Pattern>

    </layout>

  </appender>

mdc use case insertingservletfilter
MDC Use Case: InsertingServletFilter
  • %X{req.remoteHost}
  • %X{req.requestURI}%n%d - %m%n
package versions in stack traces
Package versions in stack traces

java.lang.NullPointerException

at com.xyz.Wombat(Wombat.java:57) ~[wombat-1.3.jar:1.3]

at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3]

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native) ~[na:1.5.0_06]

at java.lang.reflect.Method.invoke(Method.java:585) ~[na:1.5.0_06]

at junit.runners.TestMethod.invoke(TestMethod.java:59) [junit-4.4.jar:na]

etc..

stringutils
StringUtils

空白: defaultIfBlankdefaultIfEmptydefaultStringdeleteWhitespacenormalizeSpace

trim

判断: isAllLowerCaseisAlphaisAlphanumericisAlphanumericSpaceisAlphaSpace

isAsciiPrintableisNumericisNumericSpaceisWhitespace

isBlankisEmptyisNotBlankisNotEmpty

合分: joinsplit

结束: endsWithendsWithAnyendsWithIgnoreCase

比较: differenceequalsequalsIgnoreCasegetCommonPrefixgetLevenshteinDistance

overlay

查找: indexOfindexOfAnyindexOfAnyButindexOfDifferenceindexOfIgnoreCase

lastIndexOflastIndexOfAnylastIndexOfIgnoreCaselastOrdinalIndexOfordinalIndexOf

删除: removeremoveEndremoveEndIgnoreCaseremoveStartremoveStartIgnoreCase

替换: replacereplaceCharsreplaceEachreplaceEachRepeatedlyreplaceOnce

反转: reversereverseDelimited

子串: countMatchesleftmidrightsubstring…

补充: leftPadrepeatrightPad

大小写: capitalizelowerCaseuncapitalizeupperCaseswapCase

缩略: abbreviateabbreviateMiddle

补充: center

裁剪: chompchopstrip…

包含:containscontainsAnycontainsIgnoreCasecontainsNonecontainsOnlycontainsWhitespace

slide64

GuavaSplitter

JDKhassplitter

‣regularexpression

‣resultasanarray

‣itswayofhandlingemptypieces

(whichisverystrange)

Mini-puzzler

",a,,b,".split(",")returns...

(a)"","a","","b",""

(b)null,"a",null,"b",null

(c)"a",null,"b"

(d)"a","b"

(e)Noneoftheabove

slide65

Splitter

Breaksstringsintosubstrings

byrecognizingaseparator(delimiter),oneof:

asinglecharacter:Splitter.on('\n')

aliteralstring:Splitter.on(",")

aregex:Splitter.onPattern(",\\s*")

anyCharMatcher(rememberthat?)

orusingafixedsubstringlength

Splitter.fixedLength(8)

Iterable<String>pieces=

Splitter.on(',').split("trivial,example")

returns"trivial"and"example"inorder.

slide66

Thedefaultbehaviorissimplistic:

//yields["foo","","bar","quux",""]

Splitter.on(',').split("foo,,bar,quux,");

Ifyouwantextrafeatures,

askforthem!

//yields["foo","bar","quux"]

Splitter.on(',')

.trimResults()

.omitEmptyStrings()

.split("foo,,bar,quux,");

slide67

Guava Joiner

BizarrelyMissingFromTheJDKClassLibraries:

joiningpiecesoftextwithaseparator.

Strings=Joiner.on(",").join(episodesOnDisc);

Joinerisconfigurable:

StringBuildersb=...;

Joiner.on("|").skipNulls().appendTo(sb,attrs);

Itcanevenhandlemaps:

staticfinalMapJoinerMAP_JOINER=Joiner.on(";")

.useForNull("NODATA")

.withKeyValueSeparator(":");

string1
String到基本数据类型的转换
  • public static intparseInt(String s, int radix) throws NumberFormatException
  • public static intparseInt(String s)
  • public static byte parseByte(String s)
  • public static short parseShort(String s)
  • public static long parseLong(String s)
  • public static float parseFloat(String s)
  • public static double parseDouble(String s)
slide69
对象的字符串表示方法
  • Object类 public StringtoString()
  • String类
    • public static StringvalueOf(char c)
    • public static StringvalueOf(inti)
    • public static StringvalueOf(long l)
    • public static StringvalueOf(float f)
    • public static StringvalueOf(double d)
base64
BASE64

01 import static javax.xml.bind.DatatypeConverter.parseBase64Binary;02 import static javax.xml.bind.DatatypeConverter.printBase64Binary;0304@Test05publicvoidtestBase64(){06     String s1 ="我是黄进兵!";07     String base64 =printBase64Binary(s1.getBytes(UTF_8));08assertEquals("5oiR5piv6buE6L+b5YW1IQ==", base64);09byte[] bytes =parseBase64Binary(base64);10     String s2 =new String(bytes,UTF_8);11assertEquals(s1, s2);12}

java characters
Java Characters
  • A Java character has two bytes
  • Java supports Unicode character set standard
    • ASCII
  • Java uses UTF-16 encoding
  • Other unicode encodings:
    • UTF-8
    • UTF-16
  • Other non-unicode encodings
    • Windows-1256
java i o classes
Java I/O Classes
  • Text I/O
    • Stream of characters (Unicode format)
    • Support provided by Reader and Writer
  • Binary I/O
    • Stream of bytes (raw format)
    • Support provided by InputStream and OutputStream
    • An InputStream reads raw octet (8 bit) data (byte).
reader inputstream
Reader和InputStream区别
  • Reader和InputStream分别是I/O库提供的两套平行独立的等级机构
  • InputStream、OutputStream是用来处理8位元的流,Reader、Writer是用来处理16位元的流。
  • InputStream、OutputStream是用来处理8位元的流,Reader、Writer是用来处理16位元的流。所以在处理中文的时候需要用Reader和Writer。
  • InputStreamReader、OutputStreamWriter负责进行InputStream到Reader的适配和由OutputStream到Writer的适配。
  • intcopy(InputStream input, OutputStream output)
  • voidcopy(InputStream input, Writer output, String encoding)
  • voidcopy(Reader input, OutputStream output, String encoding)
  • intcopy(Reader input, Writer output)
reader inputstream writer writeroutputstream
Reader <-> InputStreamWriter <->WriterOutputStream
  • Reader->InputStream commons-io:ReaderInputStream
  • Writer->OutputStream commons-io:WriterOutputStream
  • InputStream->Reader jdk:InputStreamReader
  • OutputStream->Writer jdk:OutputStreamWriter
  • InputStream->OutputStream?
  • Reader->Writer?
closeable
Closeable
  • Reader何时关闭?
  • Writer何时关闭?
  • InputStream何时关闭?
  • OutputStream何时关闭?
slide79

Guava

common.io

Typically:

InputSupplier<InputStream>,

OutputSupplier<Writer>,etc.

2keyinterfaces

publicinterfaceInputSupplier<T>{

TgetInput()throwsIOException;

}

publicinterfaceOutputSupplier<T>{

TgetOutput()throwsIOException;

}

ThisletsallGuava’sutilitiesbeusefulformanykindsofI/O.

Terminology

‣bytestreammeans"InputStreamorOutputStream"

ByteStreamsutilitiesclass

‣charstreammeans"ReaderorWriter."

CharStreamsutilitiesclass

slide80

common.io:ByteStreams

byte[]toByteArray(InputStream)

byte[]toByteArray(InputSupplier)

voidreadFully(InputStream,byte[])

voidwrite(byte[],OutputSupplier)

longcopy(InputStream,OutputStream)

longcopy(InputSupplier,OutputSupplier)

longlength(InputSupplier)

booleanequal(InputSupplier,InputSupplier)

InputSupplierslice(InputSupplier,long,long)

InputSupplierjoin(InputSupplier...)

CharStreamsissimilar,butdealsinReader,Writer,Stringand

CharSequence(oftenrequiringyoutospecifyaCharset).

slide81

common.io:Files

TheFilesclassworksonelevelhigherthanByteStreamsand

CharStreams,andhasafewothertricks.

byte[]toByteArray(File)

StringtoString(File,Charset)

voidwrite(byte[],File)

voidwrite(CharSequence,File,Charset)

longcopy(File,File)

longcopy(InputSupplier,File)

longcopy(File,OutputSupplier)

longcopy(File,Charset,Appendable)

longmove(File,File)

booleanequal(File,File)

List<String>readLines(File,Charset)

slide82

MoreaboutFiles

FilecreateTempDir()

voiddeleteDirectoryContents(File)

voiddeleteRecursively(File)

longgetChecksum(File,Checksum)

byte[]getDigest(File,MessageDigest)

StringreadFirstLine(File,Charset)

List<String>readLines(File,Charset)

TreadLines(File,Charset,LineProcessor<T>)

StringtoString(File,Charset)

slide83

Flushables and Closeablesb

Flushables.flushQuietly(Flushableflushable)

Flushables.flush(

Flushableflushable,

booleanswallowIOException)throwsIOException

Closeables.closeQuietly(Closeablecloseable)

Closeables.close(

Closeablecloseable,

booleanswallowIOException)throwsIOException

Veryusefullinfinallyblocks

(avoidnestingtry/catch)

java collection interfaces
Java Collection Interfaces

4种基本形式,前三种的父接口是Collection。

1:List 关注对象的索引列表

2:Set 关注对象的唯一性

3:Queue 关注对象被处理时的顺序

4:Map 关注映射和键值的唯一性

slide97

Multimap

ListMultimap & SetMultimap

Map<String, List<T>> & Map<String, Set<T>>

Operations: put(K, V), putAll(K, Iterable<V>),

remove(K, V), removeAll(K, Iterable<V>),

replaceValues(K, Iterable<V>)

slide99

BiMap

BiMap<K, V> is Map<K,V> with unique values

Operations: all Map, inverse(), values() as Set

Throws an IllegalArgumentException if you

attempt to map a key to an already-present

value

slide102

Copy!

Lists.newArrayList()

Lists.newLinkedList()

Sets.newHashSet()

Sets.newLinkedHashSet()

Sets.newTreeSet()

ormakeitimmutable...

ImmutableList.copyOf()

ImmutableSet.copyOf()

slide103
不同集合类型有不同的时间复杂度

Depending on the size, different types of collections may behave better that others

slide105
泛型练习
  • 泛型改造MyStack
  • 增加方法: pushAll
  • 增加方法: popAll

@Test

publicvoidtestStack() {

MyStack<Number> numberStack = newMyStack<Number>();

Collection<Integer> integers = newArrayList<Integer>();

integers.add(1);

numberStack.pushAll(integers);

Collection<Object> objects = newArrayList<Object>();

numberStack.popAll(objects);

}

the get and put principle
The Get and Put Principle

publicstatic <T> void copy(List<? super T> dest, List<? extends T> src)

use anextendswildcard when you onlygetvalues out of a structure,

use asuperwildcardwhen you onlyputvalues into a structure,

and don't use a wildcard when youbothget and put.

A Mnemonic for Wildcard Usage

• PECS—Producer extends, Consumer super

– use Foo<? extends T> for a T producer

– use Foo<? super T> for a T consumer

• Only applies to input parameters

– Don’t use wildcard types as return types

slide107
Misc.
  • Tuples
  • The of-Operator
  • ULong, UInt, UShort
metadata
Metadata

Javastoresmetadatainclasses

n

Metadataforaclass:

Metadataforaconstructor:

Metadataforafield:

Metadataforamethod:

java.lang.Class

java.lang.reflect.Constructor

java.lang.reflect.Field

java.lang.reflect.Method

-

-

-

-

TwowaystoaccessaClassobjectforaclass:

Classc1=Class.forName(“java.util.Properties”);

Objectobj=...;

Classc2=obj.getClass();

Reflectionclassesareinter-dependent

n

n

Examplesareshownonthenextslide

-

examples of inter relatedness of reflection classes
Examplesofinter-relatednessofreflectionclasses

classClass{

Constructor[]

Field

Field[]

Method[]

getConstructors();

getDeclaredField(Stringname);

getDeclaredFields();

getDeclaredMethods();

...

}

classField{

ClassgetType();

...

}

classMethod{

Class[]getParameterTypes();

Class

...

getReturnType();

}

metadata for primitive types and arrays
Metadataforprimitivetypesandarrays

JavaassociatesaClassinstancewitheachprimitivetype:

Classc1=int.class;

Classc2=boolean.class;

Classc3=void.class;

Mightbereturnedby

Method.getReturnType()

UseClass.forName()toaccesstheClassobjectforanarray

Class

Class

Class

Class

c4

c5

c6

c7

=

=

=

=

byte.class;//byte

Class.forName(“[B”);//byte[]

Class.forName(“[[B”);//byte[][]

Class.forName(“[Ljava.util.Properties”);

EncodingschemeusedbyClass.forName()

Bàbyte;Càchar;Dàdouble;Fàfloat;Iàint;Jàlong;

Lclass-nameàclass-name[];Sàshort;Zàboolean

Useasmany“[”sastherearedimensionsinthearray

miscellaneous class methods
MiscellaneousClassmethods

HerearesomeusefulmethodsdefinedinClass

classClass{

publicStringgetName();//fully-qualifiedname

publicbooleanisArray();

publicbooleanisInterface();

publicbooleanisPrimitive();

publicClassgetComponentType();//onlyforarrays

...

}

invoking a default constructor
Invokingadefaultconstructor

UseClass.newInstance()tocallthedefaultconstructor

Example:

abstractclassFoo{

publicstaticFoocreate()throwsException{

StringclassName=System.getProperty(

“foo.implementation.class”,

“com.example.myproject.FooImpl”);

Classc=Class.forName(className);

return(Foo)c.newInstance();

}

abstractvoidop1(...);

abstractvoidop2(...);

}

...

Fooobj=Foo.create();

obj.op1(...);

a plug in architecture
Aplug-inarchitecture

Useapropertiesfiletostoreamappingfor

pluginnameàclassname

Manytoolssupportplugins:Ant,Maven,Eclipse,…

abstractclassPlugin{

abstractvoidop1(...);

abstractvoidop1(...);

}

abstractclassPluginManager{

publicstaticPluginload(Stringname)

throwsException{

StringclassName=props.getProperty(name);

Classc=Class.forName(className);

return(Plugin)c.newInstance();

}

}

...

Pluginobj=PluginManager.load(“...”);

invoking a non default constructor
Invokinganon-defaultconstructor

Slightlymorecomplexthaninvokingthedefaultconstructor:

-UseClass.getConstructor(Class[]parameterTypes)

-ThencallConstructor.newInstance(Object[]parameters)

abstractclassPluginManager{

publicstaticPluginload(Stringname)

throwsException{

StringclassName=props.getProperty(name);

Classc=Class.forName(className);

Constructorcons=c.getConstructor(

newClass[]{String.class,String.class});

return(Plugin)cons.newInstance(

newObject[]{“x”,“y”});

}

}

...

Pluginobj=PluginManager.load(“...”);

passing primitive types as parameters
Passingprimitivetypesasparameters

Ifyouwanttopassaprimitivetypeasaparameter:

Wraptheprimitivevalueinanobjectwrapper

Thenusetheobjectwrapperastheparameter

Objectwrappersforprimitivetypes:

à

à

à

à

boolean

byte

char

int

...

java.lang.Boolean

java.lang.Byte

java.lang.Character

java.lang.Integer

-

-

-

-

-

invoking a method
Invokingamethod

Broadlysimilartoinvokinganon-defaultconstructor:

UseClass.getMethod(Stringname,

Class[]parameterTypes)

ThencallMethod.invoke(Objecttarget,

Object[]parameters)

Objectobj=...

Classc=obj.getClass();

Methodm=c.getMethod(“doWork”,

newClass[]{String.class,String.class});

Objectresult=m.invoke(obj,newObject[]{“x”,“y”});

looking up methods
Lookingupmethods

TheAPIforlookingupmethodsisfragmented:

Youcanlookupapublicmethodinaclassoritsancestorclasses

Or,lookupapublicornon-publicmethoddeclaredinthespecifiedclass

-

-

Abettername

wouldhavebeen

getPublicMethod()

classClass{

publicMethodgetMethod(Stringname,

Class[]parameterTypes);

publicMethod[]getMethods();

publicMethodgetDeclaredMethod(Stringname,

Class[]parameterTypes);

publicMethod[]getDeclaredMethods();

...

}

finding an inherited method
Findinganinheritedmethod

Thiscodesearchesupaclasshierarchyforamethod

-Worksforbothpublicandnon-publicmethods

MethodfindMethod(Classcls,StringmethodName,

Class[]paramTypes)

{

Methodmethod=null;

while(cls!=null){

try{

method=cls.getDeclaredMethod(methodName,

paramTypes);

break;

}catch(NoSuchMethodExceptionex){

cls=cls.getSuperclass();

}

}

returnmethod;

}

accessing a field
Accessingafield

Therearetwowaystoaccessafield:

Byinvokingget-andset-stylemethods(iftheclassdefinesthem)

Byusingthecodeshownbelow

Objectobj=...

Classc=obj.getClass();

Fieldf=c.getField(“firstName”);

f.set(obj,“John”);

Objectvalue=f.get(obj);

-

-

looking up fields
Lookingupfields

TheAPIforlookingupfieldsisfragmented:

Youcanlookupapublicfieldinaclassoritsancestorclasses

Or,lookupapublicornon-publicfielddeclaredinthespecifiedclass

-

-

Abettername

wouldhavebeen

getPublicField()

getField(Stringname);

getFields();

getDeclaredField(Stringname);

getDeclaredFields();

wouldhavebeen

getPublicField()

classClass{

publicField

publicField[]

publicField

publicField[]

...

}

finding an inherited field
Findinganinheritedfield

Thiscodesearchesupaclasshierarchyforafield

Worksforbothpublicandnon-publicfields

-

FieldfindField(Classcls,StringfieldName)

{

Fieldfield=null;

while(cls!=null){

try{

field=cls.getDeclaredField(fieldName);

break;

}catch(NoSuchFieldExceptionex){

cls=cls.getSuperclass();

}

}

returnfield;

}

java modifiers
Javamodifiers

Javadefines11modifiers:

n

abstract,final,native,private,protected,public,static,

strictfp,synchronized,transientandvolatile

-

Someofthemodifierscanbeappliedtoaclass,methodor

field:

n

Setofmodifiersisrepresentedasbit-fieldsinaninteger

AccesssetofmodifiersbycallingintgetModifiers()

-

-

Usefulstaticmethodsonjava.lang.reflect.Modifier:

n

static

static

static

static

...

boolean

boolean

boolean

boolean

isAbstract(intmodifier);

isFinal(intmodifier);

isNative(intmodifier);

isPrivate(intmodifier);

accessing non public fields and methods
Accessingnon-publicfieldsandmethods

BothFieldandMethoddefinethefollowingmethods

(inheritedfromjava.lang.reflect.AccessibleObject):

booleanisAccessible();

voidsetAccessible(booleanflag);

staticvoidsetAccessible(AccessibleObject[]array,

booleanflag);

Betterterminologymighthavebeen

“SuppressSecurityChecks”insteadof“Accessible”

Exampleofuse:

if(!Modifier.isPublic(field.getModifiers()){

field.setAccessible(true);

n

n

n

Hibernateusesthistechnique

soitcanserializenon-public

joor a fluent reflection api for java
JOOR A fluent reflection API for Java

jOOR stands for Java Object Oriented Reflection.

It is a simple wrapper for the java.lang.reflect package.

String world = on("java.lang.String")// Like Class.forName().create("Hello World")// Call the most specific matching constructor.call("substring",6)// Call the most specific matching substring() method.call("toString")// Call toString().get();// Get the wrapped object, in this case a String

performance
Performance

// Method reflection with ReflectASM:

SomeClass someObject =...MethodAccess access =MethodAccess.get(SomeClass.class);access.invoke(someObject,"setName","Awesome McLovin");String name =(String)access.invoke(someObject,"getName");

comparison with standard java lang reflect
Comparison with standard java.lang.reflect

Employee[] employees = on(department).call("getEmployees").get();for(Employee employee : employees){Street street = on(employee).call("getAddress").call("getStreet").get();System.out.println(street);}

jOORcode:

try{Method m1 = department.getClass().getMethod("getEmployees");Employee employees =(Employee[]) m1.invoke(department);for(Employee employee : employees){Method m2 = employee.getClass().getMethod("getAddress");Address address =(Address) m2.invoke(employee);Method m3 = address.getClass().getMethod("getStreet");Street street =(Street) m3.invoke(address);System.out.println(street);}}// There are many checked exceptions that you are likely to ignore anyway catch(Exception ignore){// ... or maybe just wrap in your preferred runtime exception:thrownewRuntimeException(e);}

The same example with normal reflection in Java:

eclipse json editor
Eclipse json editor

{

hotelList:[

{name:"Beijing",address:"Haidian Road NO:1",price:110.0},

{name:"Beijing",address:"Haidian Road NO:2",price:120.0},

{name:"Beijing",address:"Haidian Road NO:3",price:130.0},

{name:"Beijing",address:"Haidian Road NO:4",price:140.0},

{name:"Beijing",address:"Haidian Road NO:5",price:150.0},

{name:"Beijing",address:"Haidian Road NO:6",price:160.0},

{name:"Beijing",address:"Haidian Road NO:7",price:170.0}

],

timeStamp:"Wed Oct 08 10:25:10 CST 2008"

}

slide131

WhatisJSON?

•Lightweightdata-interchangeformat

>ComparedtoXML

•Simpleformat

>Easyforhumanstoreadandwrite

>Easyformachinestoparseandgenerate

•JSONisatextformat

>Programminglanguageindependent

>UsesconventionsthatarefamiliartoprogrammersoftheC-

familyoflanguages,includingC,C++,C#,Java,JavaScript,

Perl,Python

slide132

WhyUseJSONoverXML

•LighterandfasterthanXMLason-the-wiredata

format

•JSONobjectsaretypedwhileXMLdataistypeless

>JSONtypes:string,number,array,boolean,

>XMLdataareallstring

•NativedataformforJavaScriptcode

>DataisreadilyaccessibleasJSONobjectsinyourJavaScript

codevs.XMLdataneededtobeparsedandassignedto

variablesthroughtediousDOMAPIs

>Retrievingvaluesisaseasyasreadingfromanobject

propertyinyourJavaScriptcode

slide133

JSONToolsforJavaDeveloper

•Parser

>ParseJSONtextfilesandconvertthesetoaJavamodel

•Renderer

>RenderaJavarepresentationintotext

•Serializer

>SerializeplainPOJOclusterstoaJSONrepresentation

•Validator

>ValidatethecontentsofaJSONfileusingaJSONschema

alibaba fastjson
AlibabaFastJSON

基本序列化

反序列化

json schema
JSON Schema

{

"$schema" : "http://json-schema.org/draft-03/schema#",

"id" : "http://json-schema.org/draft-03/schema#",

"type" : "object",

"properties" : {

"type" : {

"type" : ["string", "array"],

"items" : {

"type" : ["string", {"$ref" : "#"}]

},

"uniqueItems" : true,

"default" : "any"

},

"properties" : {

"type" : "object",

"additionalProperties" : {"$ref" : "#"},

"default" : {}

},

xml tools
XML tools

http://code.google.com/p/xmltool/

XMLTag tag =XMLDoc.newDocument(false).addDefaultNamespace("http://www.w3.org/2002/06/xhtml2/").addNamespace("wicket","http://wicket.sourceforge.net/wicket-1.0").addRoot("html").addTag("wicket:border").gotoRoot().addTag("head").addNamespace("other","http://other-ns.com").gotoRoot().addTag("other:foo");System.out.println(tag.toString());

xml tools features
XML tools Features
  • Create new XML documents from external sources or new document from scrash
  • Manage namespaces
  • Manipulating nodes (add, remove, rename)
  • Manipulating data (add, remove text or CDATA)
  • Navigate into the document with shortcuts and XPath (note: XPath supports namespaces)
  • Tranform an XMlDoc instance to a String or a Document
  • Validate your document against schemas
  • Executin callbacks on a hierarchy
  • Remove all namspaces (namespace ignoring)
  • ... and a lot of other features !
joox java object oriented xml
jOOX-Java Object Oriented XML

// Find the order at index for and add an element "paid"$(document).find("orders").children().eq(4).append("<paid>true</paid>");// Find those orders that are paid and flag them as "settled"$(document).find("orders").children().find("paid").after("<settled>true</settled>");// Add a complex element$(document).find("orders").append( $("order", $("date","2011-08-14"),$("amount","155"),$("paid","false"),$("settled","false")).attr("id","13");

jooq h2
JOOQ + H2

01 import org.jooq.util.h2.H2Factory;02 import cn.bingoo.h2.domain.Tables;03 import cn.bingoo.h2.domain.tables.records.VouchercardRecord;0405@Test06publicvoidtestJooq() throws Exception {07DriverManager.registerDriver(new org.h2.Driver());08     Connection conn =DriverManager.getConnection("jdbc:h2:~/bingoo-handy","sa","");09     Factory factory=new H2Factory(conn);1011VouchercardRecordnewRecord=factory.newRecord(Tables.VOUCHERCARD);12newRecord.setCode("mycode"); newRecord.setPass("mypass"); newRecord.setHmac("mymac");13newRecord.store();1415VouchercardRecordfetchOne=factory.selectFrom(Tables.VOUCHERCARD)16.where(Tables.VOUCHERCARD.CODE.equal("mycode")).fetchOne();1718assertEquals(newRecord,fetchOne);1920conn.close();21}

regular expression
Regular Expression正则表达式
  • 文本处理的利器(grep, perl, ruby, lua内嵌)
  • Perl,ruby,javascript写法 /[a-z]+/
    • Eg.name= “Dave”; name =~ /[a-z]/;找到ave
  • JDK1.4 java.util.regex
  • 一些简单例子:

[a-z]+ 匹配一个或多个小写字母

abcexactly this sequence of three letters

[abc]any one of the letters a, b, or c

[^abc] any character except one of the letters a, b, or c

(immediately within an open bracket, ^ means “not,” but anywhere else it just means the character ^)

[a-z]any one character from a through z, inclusive

[a-zA-Z0-9]any one letter or digit

abc|xyzmatcheitherabcorxyz

[A-Za-z]+[0-9] match one or more letters immediately followed by one digit

types of quantifiers
限定符类型Types of quantifiers
  • A greedy quantifier will match as much as it can, and back off if it needs to
    • We’ll do examples in a moment
  • A reluctant quantifier will match as little as possible, then take more if it needs to
    • You make a quantifier reluctant by appending a ?:X??X*?X+?X{n}? X{n,}?X{n,m}?
  • A possessive quantifier will match as much as it can, and never let go
    • You make a quantifier possessive by appending a +:X?+X*+X++X{n}+X{n,}+X{n,m}+
slide144
限定符示例
  • Suppose your text is aardvark
    • Using the pattern a*ardvark (a* is greedy):
      • The a* will first match aa, but then ardvark won’t match
      • The a* then “backs off” and matches only a single a, allowing the rest of the pattern (ardvark) to succeed
    • Using the pattern a*?ardvark (a*? is reluctant):
      • The a*? will first match zero characters (the null string), but then ardvark won’t match
      • The a*? then extends and matches the first a, allowing the rest of the pattern (ardvark) to succeed
    • Using the pattern a*+ardvark (a*+ is possessive):
      • The a*+ will match the aa, and will not back off, so ardvark never matches and the pattern match fails
java regex
JAVA中的Regex

01 import java.util.regex.Matcher;02 import java.util.regex.Pattern;03 04 @Test05 publicvoidtestRegex() {06     Pattern p =Pattern.compile(“[a-z]+”);07     String text =“Hello world”;08     Matcher m =p.matcher(text);09 assertTrue(m.find());10 assertEquals("ello",text.substring(m.start(),m.end()));11 assertTrue(m.find());12 assertEquals("world",text.substring(m.start(),m.end()));13 assertFalse(m.find());14 }

capturing groups
分组Capturing groups
  • In regex, parentheses are used for grouping, but they also capture (keep for later use) anything matched by that part of the pattern
    • Example:([a-zA-Z]*)([0-9]*) matches any number of letters followed by any number of digits
    • If the match succeeds,\1 holds the matched letters and \2holds the matched digits
    • In addition,\0holds everything matched by the entire pattern
  • Capturing groups are numbered by counting their opening parentheses from left to right:
    • ( ( A ) ( B ( C ) ) )1 2 3 4\0 = \1 = ((A)(B(C))), \2 = (A), \3 = (B(C)), \4 = (C)‏
  • Example:([a-zA-Z])\1 will match a double letter, such asletter
java regex group replace
JAVA中的regexgroup和replace

01@Test02publicvoidtestBasicGroup() {03     Pattern p =Pattern.compile("((\\d+)\\s+(boys|girls))");0405     String text ="There are total 15 boys and 12 girls in class 1.";06     Matcher m =p.matcher(text);07assertTrue(m.find());08assertEquals("15 boys",m.group(1));09assertEquals("15",m.group(2));10assertEquals("boys",m.group(3));11assertTrue(m.find());12assertEquals("12 girls",m.group(1));13assertEquals("12",m.group(2));14assertEquals("girls",m.group(3));15assertFalse(m.find());16}1718@Test19publicvoidtestReplace() {20     String text ="There are total 15 boys and 12 girls in class 1.";21     String replacedText=text.replaceAll("(\\d+)\\s+boys","$1 men");22assertEquals("There are total 15 men and 12 girls in class 1.",replacedText);23}

string2
String类中的正则
  • public boolean matches(String regex)‏
  • public String replaceFirst(String regex, String replacement)‏
  • public String replaceAll(String regex, String replacement)‏
  • public String[ ] split(String regex)
  • public String[ ] split(String regex, intlimit)‏
    • If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
    • If n is non-positive then the pattern will be applied as many times as possible
matcher
Matcher类中的方法
  • If m is a matcher, then
    • m.replaceFirst(replacement) returns a new String where the first substring matched by the pattern has been replaced by replacement
    • m.replaceAll(replacement)returns a new String where every substring matched by the pattern has been replaced by replacement
    • m.find(startIndex)looks for the next pattern match, starting at the specified index
    • m.reset()resets this matcher
    • m.reset(newText)resets this matcher and gives it new text to examine (which may be a String, StringBuffer, or CharBuffer)‏
slide153

Pragmatic

runs on the JVM

Martin Odersky

Since

2003

Seamless Java

interoperability

Production

ready

Statically typed

Hybrid

slide154

“I can honestly say if someone had shown me the Programming Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.“

James Strachan, creator of Groovy

slide155

“If I were to pick a language to use today other than Java, it would be Scala.”

James Gosling

slide157

一切值都是对象的实例

JVM中的原生类型是对象的实例

123.toByte

"1".toInt

true.toString

函数也是值,从而也是对象的实例

valcompare=(x:Int,y:Int)=>x>y

compare(1,2)//result:Boolean=false

Java的static方法和域再没有存在的理由,因为它们的所有者

也必须是对象的实例(值),所以有了Scala中的单例object

objectDog{

valwhatever="dog"//staticfieldinJava

}

classDog{

defcallWhatever=Dog.whatever

}

slide158

函数作为值

可以当作参数传递

valcompare=(x:Int,y:Int)=>x>y

listsortWithcompare

不管它是实例的方法

classAComparator{

defcompare(x:Int,y:Int)=x>y

}

listsortWith(newAComparator).compare

还是匿名子句

objectannonymousextendsscala.Function2[Int,Int,Boolean]{

overridedefapply(x:Int,y:Int)=x>y

}

listsortWithannonymous

没有了sta&c域,一切函数,包括object的方法调用现在都是

值(实例)的方法

slide159

一切操作都是函数调用(1)

只有一个参数或零个参数的方法在调用时可以省略”.”和”()”

1.+(1)

1+1

1.>(0)

1>0

(1>0).&(2>1)

(1>0)&2>1

stack.push(10)

stackpush10

stack.pop

stackpop

参数也可以是一系列操作{...}

stackpush{

val

val

a+

a=1

b=2

b

}

更多的符号需要用作方法名

def!@#%^&*\-<=>?|~:/=println("noop")

def√(x:Double)=Math.sqrt(x)

valΠ=Math.Pi

valr=√(9*Π)

‘<’, ‘>’更适合作方法名,所以用’[’和‘]’来表示类型参数

slide160

一切操作都是函数调用(2)

for语句是函数调用

for(i<-List(1,2)){

println(i)

}

List(1,2)foreach{i=>println(i)}

for(i<-List(1,2))yield{

i+10

}

List(1,2)map{i=>i+10}

更多的例子

//synchronizedisfunctioncallinsteadofkeyword

defcheck=synchronized{

//isInstanceOfisfunctioncallinsteadofkeyword

100.isInstanceOf[String]

}

额外的好处:自左向右顺序书写语句

stack.pop.asInstanceOf[Int]//(Integer)stack.pop()inJava

slide161

一切操作都返回值

默认返回最后一条语句的值,也可以用return显式返回

valr1={//return3

vala=1

valb=2

a+b

}

valr2=if(true)1else2

valr3=//return():Unit

for(i<-List(1,2)){

println(i)

}

valr4=//returnList(11,12)

for(i<-List(1,2))yield{

i+10

}

valr5=//returnjava.io.File

try{

valf=newFile("afile")

f

}catch{

caseex:IOException=>null

}

slide162

Higher Level

// Java – Check if string has uppercase character

booleanhasUpperCase = false;

for(inti = 0; i < name.length(); i++) {

if(Character.isUpperCase(name.charAt(i))) {

hasUpperCase = true;

break;

}

}

// Scala

valhasUpperCase = name.exists(_.isUpperCase)

slide163

Declaring classes

…concisely

// Java

public class Person {

private String name;

privateint age;

public Person(String name, int age) {

this.name = name;

this.age = age;

}

public String getName() {

return name;

}

publicint getAge() {

return age;

}

publicvoid setName(String name) {

this.name = name;

}

publicvoid setAge(int age) {

this.age = age;

}

}

// Scala

class Person(

var name: String,

var age: Int

)

java working with person

Scala – Pattern Matching

Java – working with Person

Object x = new Person("Bill Clinton", 64);

if(x instanceof Person) {

Person p = (Person)x;

System.out.println(„Person name: "+p.getName());

} else {

System.out.println("Not a person");

}

x = "Lukasz Kuczera";

if(x instanceof Person) {

Person p = (Person)x;

System.out.println("hello "+p.getName());

} elseif(x instanceof String) {

String s = (String)x;

if(s.equals("Bill Clinton"))

System.out.println("Hello Bill");

elseSystem.out.println("hello: "+s);

} elseSystem.out.println("err, ???");

var x: Any = Person("Lukasz", 28);

x match {

case Person(name, age) =>

println("Person name: "+name);

case _ => println("Not a person")

}

x = "Lukasz Kuczera"

x match {

case Person(name, age) =>

println("Person name: "+name)

case"Bill Clinton" => println("hello Bill")

case s: String => println("hello "+s)

case _ => "err, ???"

}

Person name: Lukasz

hello Lukasz Kuczera

slide165

Pattern matching

…is concise

// Java

button.addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {

System.out.println(“I see it!”);

}

public void mouseExited(MouseEvent e) {

System.out.println(“Lost it.”);

}

public void mouseClicked(MouseEvent e) {

System.out.println(“Poked!”);

}

}

// ...alternative - isinstanceof

// Scala

reactions += {

case m: MouseEntered =>

println(“I see it!”)

case m: MouseExited =>

println(“Lost it.”)

case m: MouseClicked =>

println(“Poked!”)

}

slide166

Working with arrays

// Java

publicclass Partition {

Person[] all;

Person[] adults;

Person[] minors;

{

ArrayList<Person> minorsList = new ArrayList<Person>();

ArrayList<Person> adultsList = new ArrayList<Person>();

for(int i=0; i<all.length; i++ ) {

(all[i].age<18 ? adultsList: minorsList).add(all[i]);

}

minors = (Person[]) minorsList.toArray();

adults = (Person[]) adultsList.toArray();

}

}

// Scala

val all: Array[Person]

val (minors, adults) = all.partition(_.age<18)

duck typing
Duck Typing

class Duck {

defquack = "呱...呱..."

}

defdoQuack(d: {def quack: String}) {

println(d.quack)

}

doQuack(new Duck)

nice to know
Nice to know

Scala:

Console.println(“Hello”)

println(“Hello”)

val line = Console.readLine()

val line = readLine()

error(“Bad”)

1 + 1

1 .+(1)

1 == new Object

1 eq new Object

"""A\sregex""".r

Java:

System.out.println(“Hello”);

BufferedReader r = new BufferedReader(new InputStreamRead(System.in)

String line = r.readLine();

throw new RuntimeException(“Bad”)

new Integer(1).toInt() + new Integer(1).toInt();

new Integer(1).equals(new Object());

new Integer(1) == new Object();

java.util.regex.Pattern.compile(“A\\sregex”);

slide169

“A little learning is a dangerous thing; drink deep, or taste not the Pierian spring: there shallow draughts intoxicate the brain, and drinking largely sobers us again.” --Alexander Pope

学识浅薄是件危险的事情;

要么酣饮,不然就尝不到知识源泉的甘霖。

在那里浅斟薄饮使头脑醉昏,

大量畅饮会使我们清醒。

--亚历山大·蒲柏