Java: Where is the method? - java

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.

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

How imports of static libraries work in Java / Spring?

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.

Using a global (static) variable in Java

I have a need to share a variable between two classes in the same package. I would not like to debate the "why" I'm using a global variable. I avoid them normally at all cost.
My understanding is that I need to declare my variable as static, and that any variable declared in such a manner is available to all classes in the package. I am using a Java library called Lanterna that is used to create text-based GUIs. In order write characters to the screen buffer, I have to create an object (which I called screen) of the Screen type. The two declarations below are placed near the top of my entry class (not in the constructor).
public static Terminal terminal = TerminalFacade.createTerminal(System.in, System.out, Charset.forName("UTF8"));
public static Screen screen = new Screen(terminal);
The types Terminal and Screen are declared as import statements at the top of my program. I don't receive any errors in Eclipse with these statement. In the class where I attempt to access the screen object, I get an error saying Multiple Markers at this line, screen cannot be resolved.
If any additional information needs to be provided please let me know.
While terminal and screen are in-scope everywhere, they are not automatically imported, and you have to reference them by the class that contains them.
For example, if you declared them in class Myclass, you would access them by eg.
MyClass.terminal.frobnicate();
Alternatively, though this is not standard practice in most cases, you can import them like so:
import static myPackage.MyClass.terminal;
Then you will be able to simply reference terminal without clarifying that you refer to MyClass's terminal, and not some other class's static field called terminal.
Instead of import you need a static import (The Static Import Java guide says, in part, The static import construct allows unqualified access to static members without inheriting from the type containing the static members). Something like (obviously with your entry-class)
import static com.foo.EntryClass.terminal;
import static com.foo.EntryClass.screen;

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

import static does not work when the class has methods with the same name as the imported ones

I have a Junit4 test case which statically imports the org.junit.Assert.assertEquals method(s).
import static org.junit.Assert.assertEquals;
In this class I have created a utility method for asserting some complex internal classes which do not implement equals (and also have a hard time implementing it).
private void assertEquals(MyObj o1, MyObj o2)
{
assertEquals(o1.getSomething(), o2.getSomething());
assertEquals(o1.getSomethingElse(), o2.getSomethingElse());
...
}
I expected the code to behave as if I am "overloading" the assertEquals method(s) that I'm importing, but it looks like my private non-static method is hiding the statically imported methods. I also tried turning my method to be public and static (all permutations) but with no success - I had to rename it.
Any reason why it behaves this way? I couldn't find any reference to this behavior in the documentation.
What you observed is calling Shadowing. When two types in java have the same simple name, one of them will shadow the other. the shadowed type then can't be used by it's simple name.
The most common type of shadowing is a parameter to hide a field. usually result in setter code to look like setMyInt(int myInt) {this.myInt = myInt; }
Now let's read the relevant documentation:
A static-import-on-demand declaration never causes any other declaration to be shadowed.
This indicate a static import on demand always comes last, so any type with the same simple name as a import on demand declaration will always shadow (hide) the static import.
Overloading and overwriteing works in an inheritance tree. But a static import doesn't build a inheritance.
If you want to use the assertEquals of junit in your own assertEquals method you must qualify it with the className e.g. Assert.assertEquals.
Use a nonstatic import of org.junit.Assert.
You have stumbled onto method hiding, where the presence of a local method "hides" one from another class (often a super class).
I have always felt that statically importing methods is, while syntactically possible, somehow "wrong".
As a style, I prefer to import the class and use TheirClass.method() in my code. Doing so makes it clear that the method is not a local method, and one of the hallmarks of good code is clarity.
I recommend you import org.junit.Assert and use Assert.assertEquals(...).
This makes sense. Suppose javac does what you want, it picks your assertEquals(MyObj, MyObj) method today. What if tomorrow org.junit.Assert adds its own assertEquals(MyObj, MyObj) method? The meaning of invocation assertEquals(mo1,mo2) changed dramatically without you knowing it.
At question is the meaning of the name assertEquals. Javac needs to decide that this is a name of method(s) in org.junit.Assert. Only after that, it can do method overloading resolution: examine all methods in org.junit.Assert with the name assertEquals, pick the most appropriate one.
It's conceivable that java could handle method overloading from multiple classes, however as the first paragraph shows, it causes great uncertainty to developer of which class the method he is calling. Because these classes are unrelated, method semantics can differ greatly.
If at compile time, it's without any doubt to developr which class the method belongs to, it is still possible that the class will overload the method tomorrow therefore changing the target method invoked.
However, because that is done by the same class, we can hold it responsible. For example, if org.junit.Assert decides to add a new assertEquals(MyObj, MyObj) method, it must be aware that some previous invocations of assertEquals(Object,Object) are now rerouted to the new method, and it must make sure that there's no semantics change that will break the call sites.

Categories

Resources