user4413257
user4413257

Reputation:

Ambiguous class name in Java

Currently I'm working with API which has two classes with the same name in different packages. When I want to use both in one class, I have to assign absolute package path for one of them which is in both cases too long. Is there any other way how to use both classes without using long absolute paths? For example using some kind of alias for import statement, so I could use something like this: alias.className.

Upvotes: 2

Views: 4907

Answers (3)

user4413257
user4413257

Reputation:

I've just came to the same problem again and realized, that this can be easily solved by wrapping class to a simple wrapper which will act like an alias.

public class AbstractAlias<T> {
    private final T o;
    public AbstractAlias(T o) { this.o = o; }
    public T get() { return o; }
    @Override public boolean equals(Object obj) { return o.equals(obj); }
    @Override public int hashCode() { return o.hashCode(); }
}

Creating concrete "alias" subclass

public class MyAlias extends AbstractAlias<long.class.path.ClassName> {
    public MyAlias(long.class.path.ClassName o) { super(o); }
}

Using MyAlias in generic structure e.g. Map

Map<String,MyAlias> map = new HashMap<>();

Upvotes: 1

Neeraj Jain
Neeraj Jain

Reputation: 7720

You can't import two classes with the same name and use them unqualified, and there is no such aliasing mechanism in Java.

You'll need to refer to one of the classes by its fully qualified name and only import the other one.

In your case import class having longer package name and use other with fully qualified name .

Upvotes: 1

Jeff Storey
Jeff Storey

Reputation: 57212

Not in pure Java, no. Other languages let you do that, but with Java the only thing to do is to import one and use the fully qualified name for the other.

Upvotes: 5

Related Questions