سؤال

I'm making use of a Java helper class with several static fields and methods:

doSomething(doableThing, TrackingHandler.EVENT_AREA_FINANCE, TrackingHandler.SUCCEEDED(TrackingHandler.EVENT_KEY_THING));

I'm trying to come up with a cleaner way to reference my static fields and methods, without having to repeat the TrackingHandler class name so many times.

I realize it's not quite the same idea, but something akin to C#'s "using" would be great:

using TrackingHandler
{
    doSomething(doableThing, EVENT_AREA_FINANCE, SUCCEEDED(EVENT_KEY_THING));
}

Is there a way to do this?

هل كانت مفيدة؟

المحلول

You can use static imports:

import static yourpackagename.TrackingHandler.*;

And then just use static members as:

doSomething(doableThing, EVENT_AREA_FINANCE, SUCCEEDED(EVENT_KEY_THING));

The static import construct allows unqualified access to static members without inheriting from the type containing the static members.

The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern).

Suggested Reading:

  1. What does the “static” modifier after “import” mean?
  2. JLS 7.5.3 and 7.5.4
  3. Should I use static import?

Note: If static import is used indiscriminately, it will likely make code more difficult to understand.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top