Common Library of Java knowledge that you should update

Source: Internet
Author: User
Tags log4j

In many people's eyes, Java is already an old language, but it does not prevent the Java world is still moving forward. If you've ever left Java, traveled to other worlds, or struggled with legacy code on a daily basis, maybe it's time to look up and see what's new in old Java.

Guava

Guava [Gwɑ:v], in a word, as long as you do the Java project, you should use Guava (Github). Official API.

Guava is a set of Java core libraries from Google, which, in my view, should even be part of the JDK. As a Java programmer, if you have not complained about the design of the JDK, you can only say that you are writing too few programs. It was the JDK that was poorly designed to complement the JDK. If the old Java programmer should have heard of Apache Commons Lang, what the new Java programmer should know is guava.

Older Java programmers are more aware of Google collections, may wish to go to its homepage, you will see this library has been renamed to Guava. In fact, guava is not directly equal to Google Collections,guava is a superset. Guava is really too strong, want to show its strong, need special introduction, here will not unfold.

The following is the end of this paragraph with a small program that counts the number of occurrences of a word, although it cannot be compared with the implementation of many other languages, but as a Java programmer, you might want to consider what this code should look like in the traditional way.

String content = files.tostring (new File (Args[0]), Charset.defaultcharset ());
iterable texts = Splitter.on (Charmatcher.whitespace)
                                               . Omitemptystrings ()
                                               . Trimresults ()
                                               . split (content);
Multiset collection = hashmultiset.create (texts);

In addition, Guava also offers:

  • Cache (caching), local cache implementation, support for multiple cache expiration policies);
  • Native type (primitives), which extends the primitive types (such as int, char) operations not provided by the JDK, including some types of unsigned forms;
  • Concurrent libraries (concurrency libraries), powerful and simple abstractions, make it easier to write the correct concurrency code;
  • General annotations (common annotations),
  • string processing, string tools, including splits, joins, fills, and so on;
  • Event Bus (Eventbus), component communication in publish-subscribe mode, does not need to be explicitly registered with other components;
  • I/O, simplifies I/O, especially I/O flow and file operations, for JAVA5 and 6 versions;
  • Reflection (Reflection), Guava's Java reflection mechanism tool class;
  • Hash (hash), which provides a more complex hash implementation than Object.hashcode () , and provides the implementation of the Bloom filter.
Joda Time

do you think an API is designed to be poor enough to Deprecated your own API. Java.util.Date is such a wonderful flower. Because its APIs are almost counter-intuitive, almost all Java programmers who dare to use it have eaten it. It's not that easy to initialize a first day of 2013 years:

Date firstDayOf2013 = new Date (113, 0, 1);

If you're a novice in Java, can you guess where 113 came from? (Well, it's 2013-1900, as for why 1900, this really has to ask the designer of the API).

Joda time is the product of people's inability to tolerate such things. The same code is implemented with Joda time:

DateTime firstDayOf2013 = new DateTime (). Withdate (2013, 1, 1);

In any case, you know that this can see the meaning of these parameters. Not only that, you can also count the days after two days:

Firstdate.plusdays (2);

Date formatting is also a feature of the JDK date series API, and you must write the code as follows:

New SimpleDateFormat ("yyyy. Mm.dd "). Format (firstDayOf2013)

As a constructor that initializes very slowly, you must also call every time because it is not thread-safe. The same code, in Joda time, we can use DateTimeFormatter:

DateTimeFormatter formatter = Datetimeformat.forpattern ("yyyy. Mm.dd ");
...
Formatter.print (DateTime);

Please feel free to declare formatter as a field, as it is thread-safe.

Of course, Joda time is much more powerful than that. Of course, the JDK is not completely self-defeating, so a JSR 310 is specifically designed to design a new Date API. The spec lead for JSR 310 is Steven Colebourne, who is the author of Joda time. However, although JSR 310 paints a new picture of Date for us, it is not the idea of Java 8 to get out before it comes out, just use Joda time, and download Joda. Ibm,sourceforge.

For more information about Joda time, see Joda-time profile.

hamcrest

In a word, if you write unit tests, you should use Hamcrest.

Now that you are not writing unit tests, you are embarrassed to say that you are doing a project. But you generally write assertions like this? If you still write the following, I can only say that you are outdated:

Assertequals (A, b);

please tell me, which is the result of the execution, which is the expected result, no matter what you are, anyway, in most cases, I can't remember. So, this API that was created in a heavy-weight, non-readable era is updated. So, Hamcrest was born to solve such problems.

Assertthat (A, is (b));

Obviously, the previous one is the result of the execution, and the next one is the expected result, which is, of course, just a simple example. Since Hamcrest introduced the concept of Matcher (which is the part you see), we can do more:

Assertthat (number, GreaterThan (5));
Assertthat (text, StartsWith ("Hello"));
Assertthat (Array, Hasitem ("World"));

Hamcrest so good that JUnit has absorbed it. If the JUnit you're using now is a version after 4.4, you've got hamcrest. No additional configuration is required, so you can take it with you.

Mockito

Writing unit tests without mock frames is almost impossible, I mean mock frames, not mock patterns Oh! For old Java programmers, the first thing to do with Mock frames is the Jmock or easymock that hit the line in the head.

Use Mockito, as long as there is a reason enough, simple. Compared to Jmock, it does not have to write checking, compared to easymock, it eliminates the replay. Here's an example:

List mockedlist = mock (list.class);
When (Mockedlist.get (0)). Thenreturn ("first");
System.out.println (mockedlist.get (0));

Of course, Mockito is still very powerful.

Finally, again, no matter which frame you use, try not to use verify, which is the legendary mock pattern, which is the beginning of pulling the code into the mire.

slf4j and Logback

Log is almost a little bit of the size of the project can not open a thing, if you are an old Java programmer, you must know log4j, probably also know Commons Logging. It's time to throw them away because there are slf4j and logback. SLF4J to replace Commons Logging, and Logback's goal is log4j.

The programmer is angry, slf4j and Logback's author is a, his name Ceki Gülcü, in fact, he is also the author of Log4j. Log4j's State of development really made him so uncomfortable, so he began to build a new alternative.

Just a little bit is enough to let us to slf4j, do you remember to use Commons Logging write such code?

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

and slf4j only a sentence:

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

From the root, this is caused by the times, Commons Logging is generated before Java 5, then there is no change, so we have to say, it is old.

As for Logback, performance is the most important gimmick, and of course there are other reasons. The reason is not mentioned, but for developers very intimate improvement, is the improvement of the log mode, remember log4j the same password log mode?

%D{DD MMM yyyy HH:mm:ss} [%t]%-5p%m%n

Here is the version of Logback, without checking the documentation, and I can see what each paragraph represents:

%D{DD MMM yyyy HH:mm:ss} [%thread]%-5level%msg%n

Here are a few of the libraries are very general, no matter how you do the development, should be more or less to give you some help. Time has never stopped, Java development has not stayed, if you are an old Java programmer, it is time to update their knowledge.

Common Library of Java knowledge that you should update

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.