简体   繁体   中英

Elegant way to avoid long object names (Fully Qualified Class Name)

I have a class where I use two objects that happen to have the same name. One is :

   com.google.api.services.calendar.model.Event

and the other 3ed party object with the same name, say:

   com.some.other.package.Event

Using import for both objects is not a good option because they will mask each other. Using the very longggggg names all over the code does not look good either.

Creating a "dummy" type just for the sake of changing its name:

public class CEvent extends com.google.api.services.calendar.model.Event {}     

does not seem like an elegant solution.

How can I preserve the original object name (Event) yet use a shorter path name ?

In Java it is impossible, the only way is to use full qualified names of classes. However, you can do this in other JVM based languages, such as Scala:

import com.some.other.package.Event => OtherEvent

or Groovy

import com.some.other.package.Event as OtherEvent

You can't shorten class names in Java; you can either import a class name (to use it without qualifiers) or use the fully qualified name. So at least one of the Event classes will have to be referred to by its fully qualified name. (Unless, as you say, you subclass one of them just to save on typing.)

The Java tutorials address this when discussing name ambiguities:

If a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name.

Java provides 2 ways:

  1. Use Fully Qualified Class Name for each class, which you don't want to
  2. Use class name for One class and Fully Qualified Class Name for other

Alternate, is to Sub-class the other class, and then you can use the new subclass name. (import sub-class)

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