Name conflict in Java import

Unless we change the compiler, Java missed importing x as y syntax, which would be very useful in my case: at this moment, I am studying a project that has multiple classes with the same name but belong to different packages

I think there's something similar

import com.very.long.prefix.bar.Foo as BarFoo
import org.other.very.long.prefix.baz.Foo as BazFoo

class X {
    BarFoo a;
    BazFoo b;
    ...
}

Instead, I did something similar

class X {
    com.very.long.prefix.bar.Foo a;
    org.other.very.long.prefix.baz.Foo b;
    ...
}

This seems very harmful, but in my specific case, I need to use horizontal scrolling to browse my source code, and this can make the program worse, which is already a mess

Based on your experience, what is the best practice in this case?

Solution

I think your pain, no matter which solution you use, there are two classes with the same name, which is easy to confuse

There are several solutions:

>If this is your code, just rename one (or both) > if this is a library (more likely) to import a more commonly used class, it fully conforms to the other class, as suggested by Jeff Olson. > If possible, try to avoid having them in the same class. > You can write your own barfoo and bazfoo and do nothing but extend their respective foo classes to provide them with their own names You can even define them as inner classes Example:

private BarFoo extends com.very.long.prefix.bar.Foo{
//nothing,except possibly constructor wrappers
}

private BazFoo extends com.very.long.prefix.bar.Foo{
//nothing,except possibly constructor wrappers
}

class X {
   BarFoo a;
   BazFoo b;
   //...
}

But there are some disadvantages:

>You must redefine the constructor > if you need to pass it to a function that explicitly checks its getClass, it will not be the same class

You can address these shortcomings by wrapping foo classes instead of extending them, for example:

private BarFoo {
   public com.very.long.prefix.bar.Foo realFoo;
}

private BazFoo extends com.very.long.prefix.bar.Foo{
  public com.very.long.prefix.baz.Foo realFoo;
}

class X {
    BarFoo a;
    BazFoo b;

    //Now if you need to pass them
    someMethodThatTakesBazFoo(b.realFoo);
}

Choose the simplest solution and good luck!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>