How imports of static libraries work in Java / Spring? - java

I am experimenting MockMvc of Spring framework. To call perform method of MockMvc I would need to have an import as following
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
Partial code
this.mockMvc.perform(get("/")).andExpect(view().name("homePage"));
I know get method is static, but it is the first time that I see import has static keyword. Is anyone able to explain this to me? why static keyword is required? why just method is imported? I am a bit confused with this.

It's importing the static get() method in the MockMvcRequestBuilders class. This means you can call it directly (without doing MockMvcRequestBuilders.get().)
This applies to any static method or field in another class - it's not specifically a spring / MockMvc thing. Likewise you don't need the import per-se, it just provides a shorthand notation.

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: 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.

Why won't abs() in java work?

I have always had a question about java.lang.Math: (It might by very basic)
Why do I have to Math.abs(-100) and can't to abs(-100)?
I figure that Math is a class. And abs is a static method. But why can I not simply import java.lang.Math and use abs(-100)?
You can import all the methods in Math:
import static java.lang.Math.*;
or just the one method you want:
import static java.lang.Math.abs;
Normal imports just import classes, making that class available via its short name.
abs is a static method and in order the compiler knows where it's defined, you have to specify the class (in your case - Math).
Note that you could do a static import on Math.abs and then you'd be able to just do abs(-100) instead of Math.abs(-100). In this case you'll have to add an import statement like this one:
import static java.lang.Math.abs;
Note also that in Java, unlike JavaScript and PHP, there aren't any public functions, which is why import statements are important.
java.lang.Math is statically imported in every Java Class.
static import java.lang.Math;
Every class of the java.lang package is imported that way.
As you know everything in java is within the class. So their can be only two alternatives.
Static Function and
Non Static Function
And java.lang.Math is a utility library. Creating object of this is not worth for you. so Java guys created all the functions static in this library.
And for your question you can call a member function directly if and only if they are member of same class.

How do I use enums without specifying the enum class each time?

I'm looking for a faster way to use enums as parameters. like if I have a method
void junk(EnumVar var){
Instead of typing EnumVar.VAR_1 I'd rather just type "VAR1" and then use content assist to do the rest, or have VAR_1 be acceptable alone, or even just use content assist give me some options. I know eclipse will do this when I type enumvar....
Is there any way to have eclipse help me work with enums faster? sort of how it does with switches.
Static import may be what you need.
For instance try import static foo.bar.MyEnum.VAR_1;
Yes, include a static import with the rest of your imports, like this:
import static my.package.EnumVar.*;

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().

Categories

Resources