Java 1.5 Tiger A Developers Notebook [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Java 1.5 Tiger A Developers Notebook [Electronic resources] - نسخه متنی

David Flanagan, Brett McLaughlin

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید








8.2 Using Wildcards in Static Imports


While importing a

single member is a nice addition, there are times
when you may want to import a lot of members. In these cases, you
could easily fill a page with all the import static declarations you'd
need. Luckily, wildcards work perfectly well with static imports.


8.2.1 How do I do that?


Piece of cake...just use a wildcard, as you would with normal import
statements:

     import static java.lang.Math.*;

Now you can use expressions like the following in your code:

     float foo = sqrt(abs(sin(bar)));

Again, nothing flashy here, but well worth knowing. It's possible to
import anything declared as static into the Java namespace. However,
you couldn't do something like this:

     import static java.lang.System.out.println;

That's because while out is static, the method println( ) is not. Be careful
to keep your static and non-static items straight.

NOTE

println( ) is an
instance method
of the
PrintStream class.


8.2.2 What about...


...all the code legibility lost by doing this sort of thing? It's certainly possible
to go crazy with imports, and lose all track of which methods
belong to which class. Of course, this comes from someone who almost
never uses wildcards in normal import statements:


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.GenericServlet;
// etc.

Personally, I like it to be obvious what classes are used, as opposed to
dropping an import java.io.* statement into code. But that's a stylistic
decision, not a functional one, and now Tiger lets you keep whatever
preference you choose.

As a best practice, though, I'd recommend you only use static imports if
you were going to use a static member more than three times. In other
words, there's value in the clarity of code that reads Math.sqrt( ) as
opposed to just sqrt( ), when that method is only used once in the
entire program. However, if you're using the method fifty times, then it's
just as clear to add a static import for the method and then use it without
the prefix.


/ 131