Chapter 27: NIO, Regular Expressions, and Other Packages 833
Two Pattern-Matching Options
Although the pattern-matching techniques described in the foregoing offer the greatest
flexibility and power, there are two alternatives which you might find useful in some
circumstances. If you only need to perform a one-time pattern match, you can use the
matches( )method defined byPattern. It is shown here:
static boolean matches(Stringpattern, CharSequencestr)
It returnstrueifpatternmatchesstrandfalseotherwise. This method automatically compiles
patternand then looks for a match. If you will be using the same pattern repeatedly, then
usingmatches( )is less efficient than compiling the pattern and using the pattern-matching
methods defined byMatcher, as described previously.
You can also perform a pattern match by using thematches( )method implemented by
String. It is shown here:
boolean matches(Stringpattern)
If the invoking string matches the regular expression inpattern,thenmatches( )returnstrue.
Otherwise, it returnsfalse.
Exploring Regular Expressions
The overview of regular expressions presented in this section only hints at their power. Since
text parsing, manipulation, and tokenization are a large part of programming, you will likely
find Java’s regular expression subsystem a powerful tool that you can use to your advantage.
It is, therefore, wise to explore the capabilities of regular expressions. Experiment with several
different types of patterns and input sequences. Once you understand how regular expression
pattern matching works, you will find it useful in many of your programming endeavors.
Reflection
Reflection is the ability of software to analyze itself. This is provided by thejava.lang.reflect
package and elements inClass. Reflection is an important capability, especially when using
components called Java Beans. It allows you to analyze a software component and describe
its capabilities dynamically, at run time rather than at compile time. For example, by using
reflection, you can determine what methods, constructors, and fields a class supports. Reflection
was introduced in Chapter 12. It is examined further here.
The packagejava.lang.reflectincludes several interfaces. Of special interest isMember,
which defines methods that allow you to get information about a field, constructor, or
method of a class. There are also eight classes in this package. These are listed in Table 27-4.
The following application illustrates a simple use of the Java reflection capabilities. It
prints the constructors, fields, and methods of the classjava.awt.Dimension. The program
begins by using theforName( )method ofClassto get a class object forjava.awt.Dimension.
Once this is obtained,getConstructors( ),getFields( ), andgetMethods( )are used to analyze
this class object. They return arrays ofConstructor,Field, andMethodobjects that provide
the information about the object. TheConstructor,Field, andMethodclasses define