Non-class functions in Java - java

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 )
}

Related

Java imports. Does it support import as aliasing? [duplicate]

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.

how does java know which class do we mean [duplicate]

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.

Why did my import fail in Java?

I hava a StdDraw.java under the same folder of my working file, and picture() is a method within StdDraw.java.
However, I failed adding this line to import the method, suggesting by
package StdDraw does not exist
import StdDraw.picture
How could I possibly do that? Using package? Setting path? Or any modifications? I came from python and find it a little bit weird.
You can't import non-static methods (only classes and static members), and you don't have to!
If both your classes live in the default package then you should be able to do the following without any import statements :
myStdDrawObject.picture(); // if picture is non-static
or
StdDraw.picture(); // if picture is static
Note also, that you can't use static imports on classes that live in the default package.
If you are importing into the class which is there in same package then we no need to use any import.
if you want import mthods into the class use like below. You no need to put method name at the time of the import.
import packagename.StdDraw;
After importing your class, all non static methods of the class are available into the imported class.
when should you use static import? Only use it when you'd otherwise be
tempted to declare local copies of constants, or to abuse inheritance
(the Constant Interface Antipattern). In other words, use it when you
require frequent access to static members from one or two classes. If
you overuse the static import feature, it can make your program
unreadable and unmaintainable, polluting its namespace with all the
static members you import. Readers of your code (including you, a few
months after you wrote it) will not know which class a static member
comes from. Importing all of the static members from a class can be
particularly harmful to readability; if you need only one or two
members, import them individually. Used appropriately, static import
can make your program more readable, by removing the boilerplate of
repetition of class
names.
Read more about static import:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
When importing the package you do not need to import non static methods. You can read on Java - Packages here. It is easily explained and I found it useful when learning the same concept.
Even if you do not include import for the class which is present in the same folder, then also you can create object and call method of that class and also static methods.
You can create object and call the non-static methods.
StdDraw drawObj = new StdDraw();
drawObj.picture(); // if picture is non-static method
For static method, you can call it using class name only.
StdDraw.picture(); // if picture is static method.
What I recommend is to read up on packages and how code is organized in java. It is in someway similar to python, where a directory structure is used, but more to it in java. Maybe this will help
Java Tutorial- Packages

Android efficiency importing static methods or importing the class

I've seen in some projects people importing directly a static method into an Activity or a class instead of the whole class.
My question is, knowing that a static method can be called several times (for being more accurate, 5 or more times) in the same class, is it more efficient to import the static method or it is better to call it through its class?
Your question (according to me) does seems to address the same point.
The question is if:
is calling ClassName.staticMethod() directly
or this
import static ClassName.staticMethod;
//rest of the stuff
staticMethod();
In both cases, the methods are loaded as a singleton whenever the class is called first.If you import the static method,then thats the first time or else when you use the class's method.
So it wont make a difference because the JVM/DVM (not sure about ART) already has the data required.
IF however your question is regarding what modifiers to use,then this advocates static.
But as mentioned,involving static methods directly is just messy.
So now its more of a personal choice.
Read as:Do not import static methods directly unless you have a very specific reason to do so.
There is no difference in performance between static imports and import the class.
However, import the class and use the class name to call static methods is considered a better practice, because the code is more easy to read. With static imports it could be a bit confusing which methods are non-static methods of the class and which methods are static methods of other classes.

Get Eclipse to prefer static imports of nested classes

Assume we have a class FooCollection which contains a somewhat long list of static nested classes*:
public class FooCollection {
public static class FooA implements Foo {
// ...
}
public static class FooB implements Foo {
// ...
}
// ...
}
Assume now we have another class using all of these classes. Currently, Eclipse will auto-format this to import each class separately if we reference the class itself
import com.me.FooCollection.FooA;
import com.me.FooCollection.FooB;
import com.me.FooCollection.FooC;
import com.me.FooCollection.FooD;
// and then later something like
callBaz( FooA.class );
What I would prefer to avoid bloating imports and constant commits changing imports due to colleagues using IntelliJ, is having it imported as
import static com.me.FooCollection.*;
However, I can't seem to find anything to get Eclipse to do this. Is there something I am missing or any way to get Eclipse to do it this way?
Edit: I actually just checked and even new FooA() will still cause the imports to switch back to this, despite setting the start imports threshold.
*) I realize that this is not exactly a good design, but it's a legacy application and for the sake of it let's assume that the code cannot be changed.
Dave Newton is referencing the setting under "Organize Imports" in Window -> Preferences. You can set the threshold for importing using a wildcard. Looks like the default is 99 classes before going to the wildcard. If you set it at 2, it looks like it would do what you needed!
Not sure, if there is a way to make it to work globally, but there is a short cut to deal with one member at a time.
If you select FooCollection.FooA and press Ctrl + Shift + M will add the static import and also will update all other references with in that file.
I use this mostly to import Enums and constants.

Categories