简体   繁体   中英

Reusing part of the path to packages for classes with same name

I have two classes both name Foo. one is in package ver_one, and the other is in package ver_two.

Obviously I can't import both, so I use them with their full class names. The problem is that the full name is com.org.oh.my.god.why.is.this.package.name.so.long.ver_one & ver_two, respectively.

So if I have a point in the code where I need both, it will look like this:

 public com.org.oh.my.god.why.is.this.package.name.so.long.ver_one.Foo translate(com.org.oh.my.god.why.is.this.package.name.so.long.ver_two.Foo other) {
          return new com.org.oh.my.god.why.is.this.package.name.so.long.ver_one.Foo(other.getID());
    }

I would have liked to not have this repeat throughout the code. I can always import one of the two, but it's a only slightly better. I would prefer something along the lines of:

import com.org.oh.my.god.why.is.this.package.name.so.long.*;

public ver_one.Foo translate(ver_two.Foo other) {
      return new ver_one.Foo(other.getID());
}

In other languages it can be done with macros or something along those lines. Couldn't find something parallel in java.

If you are working with an IDE like Eclipse you have the option to automtically organize your imports, i would suggest you to take a look at that, it is a pretty useful function since it automatically deletes unused(not needed) imports and ads the ones you need.

Another option would be to use the star "*" (or however it is called):

com.org.oh.my.god.why.is.this.package.name.so.long.*

but that would import all classes that are inside of the package long.

Anyways, you shouldn't create 2 Objects(classes) of the same name, it can mostly be prevented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM