JAKARTA COMMONS: Use Class and Components 1 (1)

zhaozj2021-02-16  52

Keywords: Jakarta Commons Source: CCID Jakarta Commons: Using Class and Component 1 (1) Author: Vikram Goyal; cactus studio Translation dispatch time: 2003.08.07 15:33:09 Jakarta Commons is a Jakarta subproject It creates and maintains many independent software packages, which are generally independent of other frameworks or products, which collect a large number of small, practical components, mostly facing server-side programming.

The package of Commons is divided into two parts: Sandbox, the Commons Code Base. Sandbox is a test platform for verifying various ideas, planning. The components introduced herein belong to the Commons Code Base. The article will show the functions of each component, applicable, and introduce the usage by a simple example.

I. Overview

Reusability is the soul of the Jakarta Commons project. These packages have considered a reusability problem in the design phase. Some of these packages, such as the logging package used to record the logs, which is originally designed for other projects, such as Jakarta Struts projects, and it is very useful for other projects to greatly help other projects. Decide to construct a "public" storage location for these packages, this is the Jakarta Commons project.

In order to truly improve reusability, each package must not depend on other large frames or projects. Therefore, the package of the Commons project is basically independent, not only independent of other projects, but also independent of most of the other packages inside Commons. Although there are some exceptions, such as the BetwixT package is used to use the XML API, but most of them use the most basic API, the main purpose is to be able to easily call through simple interfaces.

However, due to the brilliance, many packages have become too simple, lack maintenance and support, even some of the wrong links, the document is also very poor. Most packages need us to find out their usage, and sometimes we need to analyze their applicable occasions. This article will introduce these packages one by one, hoping to help you quickly master this free code base that has accumulated many people.

Description: Jakarta Commons and Apache Commons are different, the latter is a top project of Apache Software Foundation, and the former is a sub-project for the Jakarta project, and the protagonist to be discussed herein. Behind this article refers to Jakarta's Commons.

In order to facilitate explanation, this article divides the 18 finished components of the Commons project (excluded EL, LATKA and JEXL) into a 5 class, as shown in the following table.

It must be pointed out that this classification is only for the convenience of the article, and there is no such classification in the Commons project, and the boundaries of these categories sometimes have a certain overlap.

This article first introduces the components of the Web related category and other classes. The next article will involve XML-related, packaging these two categories, and the last article specializes in the tool class.

Second, other classes

CLI, Discovery, Lang and Collections are incorporated into other classes, because they are all desirable for a clear, practical small goal.

2.1 CLI

■ Overview: CLI, Command Line Interface, is also "command line interface", which provides a unified interface for Java program access and parsing command line parameters.

■ Official resources: home page, binary, source code

■ When you apply: When you need to access the command line parameters in a unified manner. ■ Example App: Clidemo.java. Commons-cli-1.0.jar must be included in ClassPath.

■ Description:

How many times you have to redesign a new command line parameter processing method for a new application? If you can unify only a single interface, unify the input parameters (whether it is forced parameter, value or string, etc.), according to a range of rule analysis parameters, determine the path to the path to use, then it is good! The answer is in the CLI.

In the CLI, each of the parameters you want to specify in the command is an Option object. First create an OPTIONS object, add each Option object to the Options object, and then use the method provided by the CLI to resolve the user's input parameters. Option objects may require a user to enter a parameter, such as the file name must be provided on the command line. If a parameter is a must, it is necessary to explicitly specify when creating an Option object.

Here is the steps using the CLI.

// ... // 1 Create an options: options options = new options (); Options.addoption ("t", false, "current time"); // ... // 2 Create a parser, analyze input: CommandLineParser Parser = New BasicParser (); CommandLine CMD; Try {cmd = parser.parse (options, args);} catch (optionption pE) {usage (options); Return;} // ... // 3 Finally, according to user input Adopt the corresponding operation: IF (cmd.hasoption ("n")) {system.err.println ("nice to meet you:" cmd.getoptionValue ('n'));}

This is the complete process using the CLI. Of course, the CLI provides other advanced options, such as control formats and parsing processes, but basic use ideas are still consistent. See the sample program provided in this article.

2.2 Discovery

■ Overview: Discovery Components is an implementation of Discovery Pattern, and its goal is to locate and instantiate classes and other resources in a unified manner.

■ Official resources: home page, binary, source code.

■ When applies: When you want to use the best algorithm to find various implementations of the Java interface in the Java program.

■ Application example: DiscoveryDemo.java, MyInterface.java, MyImpl1.java, MyImpl2.java, MyInterface. It is required to include Commons-Discovery.jar and Commons-Logging.jar in ClassPath.

■ Description:

Discovery means "discovery", it tries to find all known implementations of an interface with the best algorithm. In the case of the service, the Discovery component is especially useful when we want to find all known providers of a service.

Consider this situation: We have written an interface for a particularly complex task. All the implementations of the interface are done in different ways to complete this complex task, and end users can choose to complete the task as needed. Then, in this case, what should the end user use to find all the available implementations of the interface (ie possible way to complete the task)? The situation described above is the so-called service-service provider system. The function of the service is described by the interface, and the service provider provides a specific implementation. The current problem is that end users should use some way to find which service providers have installed in the system. In this case, the discovery component is useful, but it can not only find classes that implement specific interfaces, but also to find resources, such as images or other files. DISCOVERY follows the rules defined by the Sun's service provider system when performing these operations.

For this reason, the use of Discovery components really brings a lot of convenience. Readers Refer to the interface MyInterface.java and two implementation class MyImpl1.java, MyIMple2.java, in this article. When using Discovery, you should put it in the meta-inf / service directory, pay attention to the full qualified name of the file corresponding to the interface, if the interface belongs to a package, the name of the file is also It must be changed accordingly.

// ... // 1 Create an instance of a class loader. ClassLoaders Loaders = ClassLoaders.GetApploaders (MyInterface.class, getClass (), false); // ... // 2 Use discoverclass instance to find the implementation class. DiscoverClass discover = new DiscoverClass (loaders); // ... // ③ lookup implements the specified interface class: Class implClass = discover.find (MyInterface.class); System.err.println ( "Implementing Provider:" implClass.getName ())

Run the above code, you can get the class registered in the MyInterface file. Remind again that if your implementation is in the package, the name registered here should also be modified accordingly. If the file is not placed in the correct location, or the implementation class of the specified name cannot be found or instantiated, the program will Throw discoverexception, indicating that the implementation of the eligible condition is not found. Below is an example of the content of MyInterface file: MyImpl2 # Implementation 2.

Of course, the registration method for realizing the class is not only one, otherwise the practicality of Discovery is a big discount! In fact, according to the class finding mechanism within Discovery, the class registered according to this method will be the Class finally found by Discovery. Another commonly used registration method is to pass the name of the implementation class through the system attribute or user-defined attribute, for example, abandon the file in the meta-inf / services directory, change the java -dmyinterface = myImpl1 discoveryDemo command to run the sample program The system attribute here is the name of the interface, the value is the provider of the interface, and the result of the run is exactly the same.

Discovery can also be used to create a Singleton instance and call its method, the syntax is as follows: (MyInterface) discover.newinstance (MyInterface.class)). Mymethod () ;. Note In this example, we don't know which service provider has implemented myMethod, and even we don't have to care at all. Specific situations are related to operating this code and what service provider has been registered in the operating environment, running in different environments, the actual service provider may vary. 2.3 lang

■ Overview: LANG is an extension package of java.lang, adds a number of operation String features, and also supports the amount of enumeration in C.

■ Official resources: home page, binary, source code.

■ When applies: When the method provided by the java.lang package is not met, you want more features to handle String, value, and system properties; and if you want to use C style enumerations.

■ Sample application: langDemo.java, Mortgage.java, Ontv.java. Commons-lang.jar must be included in ClassPath.

■ Description:

This package provides a number of methods provided for convenient purposes, most of them are static, simplified daily encoding. The Stringutils class is one of the representatives that make developers can deal with the standard Java.lang.String package to process strings. Using these methods is simple, usually as long as the appropriate parameters are provided when calling a static method. For example, if you want to change a word's first character to uppercase, simply call: StringUtils.capitalise ("name"), the output result called the call is Name. Please browse the StringUtils API document to learn other static methods, maybe you will find some code that can be used directly. The sample program provided herein demonstrates the use of some of these methods.

Another worthless class is randomstringutils, which provides a method of generating a random string to create a random password is too convenient.

The NumberUtils class provides methods for processing numerical data. Many methods are worthwhile, such as finding the maximum, minimum method, converts String to a numerical method, and so on. The NumberRange and the Charrange class provide a way to create and operate numerical ranges, and character ranges.

The class in the Builder package provides some special methods, which can be used to construct the Tostring, Hashcode, Compareto and Equals methods. Its basic ideas is to construct high quality Tostring, Hashcode, Compareto, and Equals methods, The user defines these methods, as long as the method in the Builder package is called. For example, we can use toStringBuilder to construct a class of TSTRING description, as shown in the following example:

Public class mortgage {private float rate; .... PUBLIC STRING TOSTRING () {Return New TostringBuilder (this). Append ("rate", this.rate). Append ("Years", this.Year . TOSTRING ();}}

1 2 3 Next >>

转载请注明原文地址:https://www.9cbs.com/read-19780.html

New Post(0)