class or method alias in java

前端 未结 8 1016
青春惊慌失措
青春惊慌失措 2020-12-10 00:31

I have long java class and method names

LONGGGGGGGGGGGGGGGClass.longggggggggggggggggggggggggMethod();

I want to alias it to g.m();

8条回答
  •  时光说笑
    2020-12-10 00:59

    The Java language provides no aliasing mechanism.

    However, you could ease your "pain" somewhat by some combination of the following:

    • For static methods, you can use static imports to avoid having the long class name.

    • You could declare your own convenience class with a short name and short method names, and implement the static methods to delegate to the real methods like:

      public static void shortName(...) { VeryLongClassName.veryLongMethodName(...); }

    • For regular methods, you could implement a Wrapper class, or a subclass with more convenient method names. However, both have downsides from the maintenance and (depending on your JVM) performance perspectives.

    • In Java 8 and later, you could potentially take a method reference, assign it to a named variable, and use that to make your calls.

    But lets step back:

    • If the real problem is that you are just fed up with typing long names, a solution is to use a modern IDE that supports completion of names as you type them. See @BillK's answer for example.

    • If the real problem is that you are fed up with the long names taking to much space, a solution is to use a wider screen / longer lines. Most monitors are big enough to display 120 character (or more) wide source code with no eye strain.

    • If neither of the above is the answer, consider just refactoring the offending code to use sensible (i.e. shorter) class and method names. Once again, a modern IDE can handle this kind of refactoring quickly and safely.

    On the last point, I would consider that the overly long class names and method names are bad style. IMO, you are justified in taking the time to fix them yourself, or suggesting that they be fixed, especially if they constitute a "public" API for some library or module.

提交回复
热议问题