Using partial package path in Java [duplicate] - java

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.

Related

Primitive function in JAVA [duplicate]

I'm mostly a c/C++/objective-C programmer, presently working in Java on an android application. My question is simple: I want a utility function, preferably not associated with any class that I can invoke from anywhere in my project (#include of some sort necessary?).
I know I can make a public static function of a class and invoke it as Class.someFunction();. I would like to just have someFunction(); I'm not sure if this is possible in java, or what the syntax for it is.
You can achieve the same "effect" by using a static import, by adding the following import in each file that you want to use it in:
import static x.y.Class.someFunction; // or x.y.Class.*;
...
// some code somewhere in the same file
someFunction();
However, all methods in Java must be part of a class. Static imports just let you pretend (briefly) otherwise.
P.S. This also works for static fields.
You could use a static import:
import static com.example.MyUtilityClass.*; // makes all class methods available
// or
import static com.example.MyUtilityClass.myMethod; // makes specified method available
You don't see this used very often because, if overused, it causes harder-to-debug code (see the last paragraph at the link above).
Here's a related question about when it's advisable to use this.
Also, following the programming best practices, You should define all such common, frequently used functionality in some utility class where you can define your functions or fields(probably constants- i.e. static and final attributes) that is going to be used/called at different places within the API.
Although, you still need to import the Utility class.
Else define such functionality in the top most parent class in your API hierarchy structure, that way you even don't have to import the class.
Hope this helps.
thanks....!!!
Yeap import static..
For instance:
import static java.lang.Math.max; // Allowing to use max method anywhere in the source
class SomeClass {
int m = max( 1, 2 );// m now is 2 due t Math.max( int, int )
}

Java Namespace - Two classes with the same name in different packages

I am coming from Objective-C where we don't have packages and namespacing.
Android has android.text.format.DateFormat which has static methods that return java.text.DateFormat instances (getLongDateFormat() and getMediumDateFormat() specifically).
Are these methods referred to as "static methods" or "class methods" or both interchangeably?
Looking at Android documentation, how am I suppose to know that the android.text.format.DateFormat methods return a java.text.DateFormat instance and not an android.text.format.DateFormat instance (returning an instance of the latter is what I initially expected)?
How do I import the necessary packages to be able to use both of these classes in my source?
Is it possible to write my implementation code this way:
DateFormat df = DateFormat.getLongDateFormat(this.getActivity());
mLabel.setText(df.format(mEvent.getDate());
The other way I would write it would be to use the full package names, but this seems unnecessary:
java.text.DateFormat df = android.text.format.DateFormat.getLongDateFormat(this.getActivity());
mLabel.setText(df.format(mEvent.getDate());
Not sure why this is downvoted, it's a useful discussion.
1) I've always heard them referred to as "static methods".
2) The only way to see it is to follow the links. The documentation is definitely misleading in this case.
3/4) The typical way to do this in java is to not import one of the classes, and fully-qualify its class name. So if you elected to import java.text.DateFormat and not the android version, you'd do something like DateFormat df = android.text.format .DateFormat.getLongDateFormat(this.getActivity());
From the JLS:
A method that is declared static is called a class method.
I would say that I hear "static method" used more often than "class method", but both are in use and should be understood by competent Java developers.
The only option would be to hover the links on the return values. This is an example of extremely poor API design, with a name conflict built in, and the android.text.format.DateFormat should have been named something like DateFormatFactory. It appears that this class may have been intended to serve the same purpose as the java.text class originally and that API compatibility left it stuck. See java.sql.Date for a similar story.
Using import is a convenience only, allowing you to use the simple class name in your code. It's always legal to use a fully-qualified class name, and the compiler translates imported class names into fully-qualified ones. You can't import multiple classes with the same name because then there's no way to distinguish them
I suggest importing the class from java.text for two reasons: You'll probably be using it more often, and it's the more "standard" class. When faced with the choice of qualifying one of two classes with the same simple name, use the simple name for the one that developers would usually assume it refers to.

Name clash in java imports

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

"Module" functionality in Java?

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.

Change Name of Import in Java, or import two classes with the same name

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.

Categories

Resources