Unless we change the compiler, Java misses the import X as Y syntax, which would be useful in cases like mine: In this very moment I'm working on a project having multiple classes with the same name, but belonging to different packages.
I would like to have something like
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 finish in having something like
class X {
com.very.long.prefix.bar.Foo a;
org.other.very.long.prefix.baz.Foo b;
...
}
Here it seems pretty harmful, but on my specific case I need to use horizontal scrolling in order to browse my source code, and that concours in making worse a program which is already a mess.
In your experience, what is the best practices in this case?
I feel your pain, whichever solution you use, the very fact that there are two classes with the same name is confusing enough.
There are several solutions workarounds:
If this is your code, just rename one of them (or both)
If this is library (which is more likely) import more commonly used class, fully qualify the other one, as Jeff Olson suggested.
Try to avoid having them in the same class in the first place if that is possible.
You could write your own BarFoo and BazFoo which do nothing other than extend their respective Foo classes thus providing them with their own names. You can even define these 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;
//...
}
There are some drawbacks, though:
You'd have to redefine the constructors
It wouldn't be the exact same class, if you need to pass it to a function which is explicitly checking its getClass.
You could solve these drawbacks by wrapping the Foo classes rather than extending them, e.g.:
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 with it!
The best practice is to refactor the code.
Either the classes should not have the same name, because it's normal to use them both in the same classes, and thus choosing the same name for both is not a wise choice. So one of them at least should be renamed.
Or it's not normal to use them both in the same classes because they belong to completely different abstraction levels (like database access code and UI code, for example), and code should be refactored to use each class where it must be used and not elsewhere.
What I've typically done in these situations is to import the most commonly used Foo in my class, and then fully-qualify the other one:
import com.very.long.prefix.bar.Foo
class X {
Foo a;
org.other.very.long.prefix.baz.Foo b;
...
}
OP here.
With time I actulally developed a strategy to workaround this limitation of the Java language. I don't know if this has some drawback (so far I've never found any), but if so please comment in this question.
The idea is to replace the last part of the fully-qualified name with a class instead of a package, and have actual classes defined as static inner-classes.
class Bar {
static class Foo { ... }
}
In this way we have something like
import f.q.n.Bar
import other.f.q.n.Baz
...
Bar.Foo a;
Bar.Foo b;
This is actually an extremely clean way of doing it. Of course it applies only to classes you control, and not on libraries.
Known drawbacks
Your boss might not like the idea and smash your finger with a hammer;
Eclipse will not like the idea, and you have to get used to it.
You may want to have a look at Kotlin, which is compatible with Java.
If there is a name clash in Kotlin, you can disambiguate by using as keyword to locally rename the clashing entity:
import foo.Bar // Bar is accessible
import bar.Bar as bBar // bBar stands for 'bar.Bar'
You can find more info at https://kotlinlang.org/docs/reference/packages.html
Related
In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.
We have application in Java, and we are using one library class. After long time after project start we got situation where, in every function we have used that class we want to add one more element in object of the class (just adding value, not adding any new member).
This change is huge. Not difficult to do, but we have used this class in 100s of functions.
Now one solution is we can inherit this class and add required change in derived class. We keep name of class same (and use fully qualified name for base class to inherit), just will change package name so we can use derived class in our code.
Is there any problem in this approach? Because my manager's suggestion is 'Its not easy as it seems to be'.
Kindly suggest if I am doing anything wrong.
Whether inheritance is the best solution depends upon the element you are trying to add. If possible consider composition over inheritance. The advantages can be found here. There you can find a example of one of the pitfall when one tries to override one of the methods. This is more possible in your case since you do not have the source code of library.
you can make small changes in the original class as long as it does not interfere with the original functioning of the class. this is better idea instead of making a derived class with the same name as base class.
If all you're adding is a single variable, this is probably safe. Anything more complicated is dangerous. I don't have any code to go on, but inheritance is probably not the right choice. What happens if you make another subclass that adds a different field, and a few months later you realize now you need both fields? Inheritance is not composable - you can't mix and match the specializations you make in subclasses. Use aggregation. If you need a Foo that also has a Bar, then make a simple container class that has both a foo and a bar:
class FooWithBar {
public final Foo foo;
public final Bar bar;
public FooWithBar(Foo foo, Bar bar) {
this.foo = foo;
this.bar = bar;
}
}
In Vb.net, we have something called a "Module" that provides a global scope whereby static functions in the module is visible throughout the entire project.
Is there such a functionality in Java ? (i.e. adding static methods that are available to multiple packages/files/classes without having the need to import .* )
Ok I am aware this is a functionality that would cause alot of debate, but really the point of this thread is not to debate about this functionality.
To answer literally, no, there's no real "global" in Java. But you don't need to import, particularly not import .*.
The code below illustrates that an import is not required but it's only really part of the answer.
package org.example.pkg.foo;
public class Foo {
public static void doSomething();
}
package org.example.pkg.bar;
public class Bar {
public void bar() {
org.example.pkg.foo.Foo.doSomething();
}
}
In Java, types, such as classes and interfaces, are defined in terms of the ClassLoader which loaded them. You can have multiple class loaders, which implies that multiple copies of the same class can be loaded. The obvious extension of this is that multiple classes with the same qualified name (package + class) can be loaded, and there's no inherent requirement that they are related.
OSGi is an example of this, where each bundle has it's own class loader, and as a result you can have multiple versions of the same class loaded at the same time.
How does this relate to the question? Well, without accurately identifying the class you want to reference it's not possible to accurately identify the method or member you want to reference. The import, or FQN referencing does that.
No, don't think so. Static imports can make it a bit less painful/verbose to use such methods, but it's generally advised to be careful with them.
Not without the import. You can declare public static methods that are accessible from anywhere in the project, but you still have to either import the class or use fully qualified class path when you use it.
public methods are visible throughout the project
however if you want to dispense with the imports you can make the path explicit
my.package.UtilClass.methodIWannaCall(someArg);
No. Import is needed for any static method to be visible.(which is a good thing).
As others mentioned, Java IDEs do this job for us.
Recently, I have been writing many classes which have, apart from generic variant, some primitive variants, for example Foo<T>, IntFoo, DoubleFoo etc. First, I used to put every variant in separate files but I soon found out that the package content has become unreadable due to large number of classes with similar names. On the other hand, putting those in a separate package often results in a loss of cohesion and extra dependencies between packages.
In the meanwhile, I have come to the idea to have the following structure:
public class Foo {
public static class TypeFoo<T> { ... }
public static class IntFoo { ... }
public static class DoubleFoo { ... }
...
}
or
public class Foo {
public static class Type<T> { ... }
public static class Int { ... }
public static class Double { ... }
}
I am interested in two things:
Does any of these two approaches result in greater overhead when using only one inner class (e.g. int-variant of the class), compared to one-class-per-file approach? Does this overhead, if any, applies when there are inner interfaces instead?
Which of these two approaches is better, if any, or if none is good, what are the alternatives?
inner classes will be more of a pain in the long run, in my opinion. if you look at the way Microsoft named their animation classes, they had the same dilemma that you did. They chose to have tons of different classes, but as a consumer of these I have found that I prefer it to be this way.
to answer your first question, there should be no overhead. When java compiles inner classes it separates them into separate *.class files anyway, so in the end the result is the same. During compilation the parser will have to sift through a lot of Foo.* references but the extra time would be negligible.
Might be completely irrelevant to what you're doing, but you could consider replacing all these classes with a Builder (or otherwise known as Fluent Interface) pattern. If these classes implement a generic interface, you shouldn't need to expose them anywhere and can still keep them inside one builder class.
A good example of this would be MapMaker which probably has zillion different inner classes but the only thing you care about is the Map or ConcurrentMap instance you get out of it.
In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.