Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly Media, Inc.The Java Series, Hardcore Java, the image of a lion, and relatedtrad
Trang 1difficult but extremely powerful and useful programming techniques like reflection,
advanced data modeling, advanced GUI
design, and advanced aspects of JDO, EJB
Trang 2and XML-based web clients This unique book reveals the true wizardry behind the complex and often-mysterious Java environment.
Trang 6Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly & Associates books may be purchased for educational,business, or sales promotional use Online editions are also
available for most titles (http://safari.oreilly.com) For moreinformation, contact our corporate/institutional sales
department: (800) 998-9938 or corporate@oreilly.com
Nutshell Handbook, the Nutshell Handbook logo, and the
O'Reilly logo are registered trademarks of O'Reilly Media, Inc.The Java Series, Hardcore Java, the image of a lion, and relatedtrade dress are trademarks of O'Reilly Media, Inc
While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein
Trang 7Studying a computer language is a career-long process Manydevelopers make the mistake of thinking that they have learnedenough They get caught in the corporate cycle of build-and-deploy and don't seek to expand their knowledge However, wecan hardly blame them for that
For one, the build-and-deploy cycle is intensive and carries with
it a substantial amount of political pressure: managers don'twant you to spend days reading a book or trying out code
turnaround, and you get to spend more time playing Frisbeewith your dog
The second problem that the corporate developer has to dealwith is that the majority of computer books are often not
appropriate for the intermediate to advanced developer Whenlooking at my rather impressive computer book library, much of
it from O'Reilly, I notice that my books tend to fall into two
categories: many are introductions to concepts and most of theothers are references to concepts Although these books arevery useful, there is a distinct lack of books that target the
intermediate to advanced programmer However, there is oneshining exception in my library
In a dusty corner of my desk is a book I bought several years
Trang 8Limited) is absolutely essential for an intermediate C++
developer It begins with the assumption that you know thelanguage and then expands from there The result is a bookthat can really transform a developer from the intermediatelevel to a true guru
That is the goal of this book with regards to the Java™
language Most of the material is meant to help you avoid manycommon mistakes made by Java developers We will also covernuances of Java, idiosyncrasies of the JDK, and advanced
techniques With luck, this book will increase your productivityand your enjoyment of Java development
Trang 9This book is for the intermediate to advanced Java programmer.With that in mind, we can concentrate on the knowledge andtechniques that go into some of the most advanced Java
software available
Prerequisites and Assumptions
Functional proficiency with Java
I will largely gloss over entire areas of Java I assume thatyou understand JavaBeans™, bound properties, JDBC, andother basics
Familiarity with basic computer science
I generally won't spend a lot of time on concepts such asscoping, logic operations, inheritance, and algorithm
construction These and similar concepts will be the basisfor more detailed discussions
Familiarity with UML
The Unified Modeling Language is the best way to expressobject-oriented engineering concepts in a manner that isfamiliar to all programmers, regardless of what languagethey speak Most of the code diagrams in this book
incorporate UML
Trang 10You should be familiar with the JDK and with how to compile
a program and use its various tools in the JDK However,expertise in all packages isn't necessary
Trang 11Used for commands you enter at the command line and tohighlight new code inserted in a running example
This icon designates a note, which is an important aside to the nearby text.
This icon designates a warning.
Trang 12The code sample set for this book is massive Almost every
snippet of code from the book can be found in the downloadablesource code (http://www.oreilly.com/catalog/hardcorejv)
However, without a guide, you could get lost quickly when
surfing through the examples
Regarding the code itself, I will frequently snip out pieces youwould need to get the code to compile and run Copying thisinfrastructure code in the book would add unnecessary bulk andpotentially cloud the issue being discussed Since I assume youare experienced in Java, I will also assume you know the
housekeeping procedures used to implement pertinent
concepts
One other tactic that I commonly use is to append a number tothe name of a class or method This is designed to show
successive versions of the same class or method The goal is toemphasize the development while allowing the user to look upthe old version and play with it if he chooses For example, youshould read Country4 as Country
Finally, the code samples are very well-documented However,for brevity's sake, I will usually slice out this documentationwhen presenting code examples Although I firmly believe thatgood Javadoc documentation is important to good development,
in this book such documentation would needlessly increase thepage count without adding to the discussion
One other thing to note about the examples is that you will
often see the comment //$NON-NLS-1$ imbedded within thecode This is merely a flagging comment that tells Eclipse not tointernationalize a particular String I have snipped these
comments from the book, as they aren't relevant to the
discussions
Trang 13combine several examples from a single subject into one classfile to reduce the housekeeping code needed to run the sample.Doing a search on the method name will quickly locate the citedexample
Categories of Examples
The examples themselves can be divided into three categories.Each of these categories has a different usage paradigm thatyou should be aware of
Trang 14init:
Trang 15[javac] Compiling 1 source file to C:\dev\hcj\bin
[javac] C:\dev\hcj\src\oreilly\hcj\review\RTTIDemo.java:54: incompatible types [javac] found : oreilly.hcj.review.RTTIDemo.A
[javac] required: oreilly.hcj.review.RTTIDemo.B
[javac] b = (A)a1; // compiler error: a1 is not a B
[javac] ^
[javac] C:\dev\hcj\src\oreilly\hcj\review\RTTIDemo.java:55: inconvertible types [javac] found : oreilly.hcj.review.RTTIDemo.C
Trang 16java.lang.Object
[java] class oreilly.hcj.review.ObjectIsGod$SomeOtherClass |> class java.lang.Object
Trang 17Total time: 1 second
Although this is the actual output, most of it is trivial and
common to every use of Ant Therefore, I snip out all of thishousekeeping for the sake of brevity The emphasized lines will
be taken out when the run is presented in the book Therefore,when you run the examples, be aware that Ant is a bit moreverbose than I am
Trang 18One of the most important skills in professional development isknowing how to use tools There are a wide variety of tools
blown IDEs that do everything for you Selecting the best toolsfor the job will make you a more productive developer
available, from the standard text editor and compiler to full-UML Diagramming
For creating diagrams in UML, I use a product called Magic DrawUML, by No Magic, Inc (http://www.magicdraw.com/) This tool
is, without a doubt, the best professional UML modeling tool onthe market Rational Rose and Together can't even touch thefunctionality and quality of Magic Draw I like it so much that Ibought a copy of the Enterprise edition for myself I highly
recommend this product Although it isn't free like other tools Irecommend, it is well worth the price
IDE
The IDE I use is Eclipse 3.0M4, which happens to be the IDE Iuse professionally as well Eclipse simply has the single bestdevelopment tool on the market I don't know how I could livewithout my refactoring tools and the other goodies that comewith Eclipse You can find Eclipse at http://www.eclipse.org/.Also, I use many Eclipse plug-ins to make my job easier Theycan be found in the Community section of eclipse.org, or youcan surf the best directory of Eclipse plug-ins at http://eclipse-plugins.2y.net/eclipse/index.jsp
Trang 19For building outside of my IDE and running examples, I useApache Ant 1.5, which is available from http://ant.apache.org/.Ant is simply the best make program ever invented I take myhat of to the folks at Apache
Logging
I use Jakarta Log4J to do logging in my programs Log4J is
available from http://jakarta.apache.org/log4j/docs/index.html
In much of the sample code, there is little logging However, inproduction systems, I am a logging fanatic
For those of you that are curious, I don't use the JDK 1.4 logging mechanism because it is, in my opinion, vastly inferior to Log4J on many levels.
Jakarta Commons
Another set of libraries that I often use in my professional code
is the Jakarta Commons Libraries These libraries are availablefrom http://jakarta.apache.org/commons/index.html They
Trang 20code itself If you haven't checked out the Commons Libraries, Istrongly advise you to do so.
Trang 21This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact O'Reilly for
permission unless you're reproducing a significant portion of thecode For example, writing a program that uses several chunks
of code from this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Hardcore Java, by Robert Simmons, Jr Copyright
2001 O'Reilly Media, Inc., 0-596-00568-7."
If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
permissions@oreilly.com.
Trang 22Please address comments and questions concerning this book tothe publisher:
http://www.oreilly.com/catalog/hardcorejv
To comment or ask technical questions about this book, sendemail to:
bookquestions@oreilly.com
For more information about books, conferences, Resource
Centers, and the O'Reilly Network, see the O'Reilly web site at:
http://www.oreilly.com
Trang 23I would like to thank all of the thousands of people who haveanswered my endless questions over the years in my quest tobecome a professional software engineer Without these
anonymous thousands on the Internet, the path would havebeen much more difficult
I would also like to thank all of the junior programmers thathave worked for me and kept my eyes open to new ideas There
is nothing like a fresh mind to suggest things that are radical,untried, and, in the end, brilliant Certain people leap to mind,such as Bettina Linssen, now a senior developer Even though Ihad considered myself something of a guru in Java GUI coding,her fresh insight and ideas taught me a thing or two All yousenior developers out there would be well advised to listen tothe ideas of your junior developers You never know what theymight teach you
I would also like to extend very special thanks to Marco
Kukulies Marco started his programming career as a junior
developer working for me He excelled beyond all expectationsand demonstrated that he has that special gift that separatesthe normal programmers from the true gurus Marco is now one
understand much of my work, without his and Marco Kukulies'moral support, this book simply wouldn't have happened My
Trang 24Sa ir's wife Mirsada, and his three children Aida, Selma, andAmela Thanks for being a second family to me!
I would like to take a moment to say "Hi" to my brother Pauland my sister Debbie I currently live in Germany, and although
electronic chapters Just look for the hand reaching up
frantically for help His editing prowess has increased the
quality of my work to a level I never knew possible When I
proposed this book to O'Reilly, it was in a much rougher statethan it is now With many publishers, I would have been mostly
on my own However, O'Reilly has really worked hard to help
me make this book one that I can be proud of I have learned alot, and Brett has truly converted me from a newbie author to aprofessional
Trang 25I can hear the groans from herea review on Java? Don't worry, Iwon't bore you with all of the gory syntax details or concepts ofthe Java language that you can easily pick up in other books.Instead, I will present a conceptual review that focuses on
some various important issues that are often overlooked or
underemphasized The study of these issues will not only giveyou a better understanding of the Java language, but prepareyou for what's covered in the rest of the book You should think
of this chapter as a roving spotlight, highlighting various issues
of Java that are worthy of mention; even the intermediate andadvanced programmer will benefit from the study of these
issues
Trang 26To understand the advanced concepts of the Java language,there are a few core concepts that you must have firmly in
mind Without these concepts, much of this book will not make
a lot of sense The concepts of pointers in Java, its class
hierarchy, and RTTI (runtime type identification) are three ofthe most important on this list
1.1.1 Constant Problems with Pointers
Java and C++ use a very analogous syntax to symbolize theirinstructions to the computer's CPU In fact, there are probablymore similarities between these languages than the two
entrenched camps of supporters would like to admit One
difference between Java and C++ that is often mentioned,
though, is that Java does not use pointers.
Pointers in C++ were a constant source of problems and weredetermined to be the programming equivalent of evil incarnate.There was, and is to this day, a large group of applications inC++ that suffer from the effects of this particular wrong
Therefore, Sun decided to leave them out of Javaat least that'sthe theory
In reality, Java uses what C++ calls references In fact, other
than primitives, all variables in Java are references Referencesand pointers are very similar; both contain the memory location
of a particular object Pointers, however, allow you to do
arithmetic whereas references do not The fact that Java uses
so many references introduces some difficulties that novice andproficient Java developers often get burned by The code shown
in Example 1-1 demonstrates one of these difficulties
Trang 27vector itself Since both variables now point to the same vector,this function actually adds an element to the source vector thatwas passed into the method; this was almost certainly not thedesired effect! We will discuss how to prevent this problem in
Chapter 2
Since you can change the contents of an incoming collection,Java actually does have pointersthat is, Java references embodythe same computer science principles that pointers do So,
when someone tells you that Java doesn't have pointers, youcan correct them by saying, "Java has pointers, it just doesn'thave pointer arithmetic."
Also, Java's use of references isn't a bad thing In fact, the
references are actually necessary to the Java language Withoutthem, you would have to pass everything by value This would
Trang 28passed to a method If the object were a String, this copyingprobably wouldn't be a big deal However, if the object is a largearray or set, the copy could take a long time Therefore,
passing everything by value would make Java code run
extremely slowly Furthermore, some objects simply don't makesense to copy at all If you have a GUI panel and wish to passthe GUI panel to another component that needs to refer to it,you certainly don't want two copies of the panel floating around
types, such as int and boolean; and even these primitive typescan be treated as objects under some circumstances, such aswhen you use reflection
I would expect that most Java programmers would find this
trivial since they already know that every nonprimitive in Java is
an object The point that I am really trying to make, though, isthat every constructed type in Java descends from the class
Trang 30There are three main reasons why java.lang.Object is always
Trang 31tool With RTTI, objects become very friendly and readily tellyou what they are, how they are used, and more In Java, RTTI
is built right into the core of the virtual machine You've almostcertainly used RTTI, even if you don't realize it; it's all over theplace For example, consider that every object in Java can tellyou what type it is through the getClass( ) method Wheneveryou invoke getClass( ), you use RTTI Example 1-4 shows the
Trang 34[javac] b = (A)a1; // compiler error: a1 is not a B
[javac] ^
[javac] C:\dev\hcj\src\oreilly\hcj\review\RTTIDemo.java:55: inconvertible types [javac] found : oreilly.hcj.review.RTTIDemo.C
Trang 36before dereferencing inner As long as inner isn't null, the
method checks to see whether the set contains target This
Trang 37altered by any other evaluation, the remaining evaluations areskipped
1.2.2 Ternary Expressions
Ternary expressions look a little strange at first However, theycan be useful in making code read better For example, considerthe following code:
Trang 38Ternary statements are very useful for performing evaluationssuch as this However, you have to be aware of a few gotchas.For example, the following code will not work:
Trang 39In this statement, the user wants to make an if-then clause
Trang 40because the return of the println( ) method is void
Additionally, the statement return p.x + p.y is pure
syntactical nonsense because return is a keyword that doesn'tevaluate to anything
Although ternary expressions are useful for shortening whatwould be an otherwise long and drawn-out piece of code, theycan be cryptic to read if they are abused I recommend that youuse ternary expressions only for very small evaluations If yourevaluation is complex, you are better off going with the if-then
structure
1.2.3 Leveraging for Loops
The for loop is one of the most elegant and underused loopingstructures in the Java language Most developers use only thebasic concept of a for loop to iterate through a predefined
for loop to make your code more elegant while dealing withsome annoying programming issues
Although the techniques in this section are not necessarily
required, they do make your code look a lot nicer However, ifthere is one concept that you should take from this section, it'sthat for loops can do much more than simply cycle through