Primitive function in JAVA [duplicate] - 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: Where is the method?

I just try to understand some code of an api, by reading the source. Here is a link:
https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/browse/src/main/java/org/bukkit/configuration/MemorySection.java
In this class you can find the method public int getInt(String path, int def). This method calls toInt(val). Where can I find this method. As there is no object or class specified such as anObject.toInt(val) or ClassName.toInt(val) the method must be defined in that class or in a superclass, but I cant find it.
My questions: Is that the original source? Can you find it? Where is it?
The toInt() method comes from the class org.bukkit.util.NumberConversions.
Now, why isn't the class specified and how can this work ? If you look at the imports at the top of the file, you will see this :
import static org.bukkit.util.NumberConversions.*;
This basically means
Make available to me any public static method in in the org.bukkit.util.NumberConversions class.
This is a useful feature of Java when you want to make your code more concise. However, since the class responsible for this method is not immediately obvious, it is better to use it only for widely-user helper methods, such as toInt here.
Another typical example are the JUnit assertions. It is even explained in their javadoc :
These methods can be used directly: Assert.assertEquals(...), however, they read better if they are referenced through static import:
import static org.junit.Assert.*;
...
assertEquals(...);
You can find an import statement with static in the first line of the java file(which is nothing but the static import, imports only the methods of the class).
import static org.bukkit.util.NumberConversions.*;
You can find the method in this link. Just traverse to the class and search.

Using partial package path in Java [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.

import static method in xtned (generated java)

It is possible to import just one static method, or member in extend? I know that it is possible to import all static methods by *, like in this example ...
import static example.Types.*
But I need only one.
Yes it is possible.
import static System.out;
You can then merely write
out.println("Doobedoo");
Which will save you from typing the System.out part several times over but is potntially confusing for anyone trying to follow you code.
Use it sparingly and generally only for constants ( static final ).
If what you're looking for is something like the using keyword from C# or C++ java doesn't have that feature.
Java 5 added an import static option that allows static variables (typically constants) to be referenced without qualifying them with a class name.
For example, after
import static java.awt.Color;
It would then be possible to write
Color background = RED;
instead of
Color background = Color.RED;
Example above have been taken from: Java: packages and Import.
The site used for the example seems to be out of date, sorry any trouble this can cause
See How java import works for more detail.

what do these statements mean and is this style recommended ?

Recently i cam across a statements :
import static java.lang.System.out;
import static java.lang.System.exit;
I read these statements in some tutorial. Are these statements O.K ?
If the statements are alright what do they mean and should they be used regularly while writing code ?
They are called static imports. The effect is to allow you to use the names out and exit in your program as if they were defined in the current scope; so you can write exit(0) instead of System.exit(0).
Now, are they a good idea? Sometimes, when used sparingly, they are a good way to reduce clutter. But most of the time, they actually just make your code harder to understand. The reader will ask "Where is this out defined?" and "Where does exit() come from?" In general, you should avoid them.
But if you're writing a class that's all about processing SomeReallyLongName objects, and SomeReallyLongName defines a bunch of FINAL_CONSTANTS, importing them with static imports will save a lot of typing and a lot of clutter, and it will be pretty clear where those constants are coming from.
They are static imports. It allows you to do something like exit(0) instead of System.exit(0).
I do not recommend this for well known Java classes because it can be confusing to some. But sometimes it is useful for utility classes like Guava.
Iterables.filter(list, SomeClass.class)
is very verbose but you can make it easier to read with static imports: filter(list, SomeClass.class)
You should check with your team to see what they code guidelines are and try to be consistent.
Yes,it is perfectly alright .
This is known as static import.This allows members defined in class as static and
public to be used without specifying the class in which the field is defined.
This feature was defined in J2SE 5.0.
For example :
import static java.lang.Math.*;
import static java.lang.System.out;
// in main
out.print( max(100,200) ); // prints 200.You didn't have to use Math.max(.,.)
I think it may not be a good idea to use static imports as it'll make your code hard to read.
Yes, these statements are referred to as static imports and are perfectly valid. Take a look at the javase guide on static imports for more information.
With respect to usage, the guide states:
So when should you use static import? Very sparingly! 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.
Static imports are a new feature added in Java 1.5
The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually
There is nothing wrong with your example if you want easy access to out and exit so that you can call them directly as out.println() for example. There is nothing syntactically incorrect about it nor from a style aspect though some may argue it is "confusing" and hard to figure out where out came from, but any modern IDE can help them figure that out.
These are static import concept.These are like simple imports but having different type of concept.See here you import one function exit() and one field out and both are static in their corresponding classes(in case both here Systen is their class).After this instead of writing System.out.println() you can simply write out.println().Similarly instead of System.exit(),you can write exit().

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