I added two external .Jar's to my Java project which have the same package and file names. Now is the Question if it is possible to reference which of the Packages/Classes I want to use in an import Statement? I'm using IntelliJ
It will load the one appears in the classpath that specified first.
From specification
The order in which you specify multiple class path entries is important. The Java interpreter will look for classes in the directories in the order they appear in the class path variable
So not possible via import directly... it actually depends on the order that dependencies appears in your classpath...
Related
Within Eclipse if a class is not found and is available on classpath Eclipse can auto import the required package. What is the mechanism that allows this ?
I doubt there some repository of class files and their associated packages that Eclipse searches...
The reason I tagged this java and scala is I assume the mechanism is same for both languages.
It's as simple as searching through the whole classpath to see if it can match the class name. Then if it can, just adding the path it took to get there. There's nothing mysterious about this
The Eclipse feature simply searches the entire collection of folders in the classpath until it finds one or more matches, then it gives you those matches as options. In pseudocode:
Find Foo.class:
For Each FOLDER in CLASSPATH
For Each PATH...Foo.class Found There
import PATH...Foo.class
You can count JAR files as folders. To see their content, try this on the command-line:
jar tvf MyJar.jar
The class path includes jars containing all JRE classes.
This is part of a demo code, I am trying to learn this code
import com.jgrindall.android.connect4.lib.board.*;
What is this code doing? is a lib a folder? if it is a folder then where is it located?
It's importing all classes in the com.jgrindall.android.connect4.lib.board package. The source for this can vary - I assume it's in the com/jgrindall/android/connect4/lib/board source folders but sometimes it refers to code in an existing jar library used in the project.
Import means you want to be able to use the named classes without having to specify their full qualified name. In particular, since this import ends in *, you're saying you want to be able to use any class in the com.jgrindall.android.connect4.lib.board package by just giving the short classname -- Board rather than com.jgrindall.android.connect4.lib.board.Board
Where those classes are loaded from is a separate question, determined by your classpath and classloaders.
it is importing a PAKAGE. You can see the package as folder, and the ending wildchar means import all class in the packge.
If you are using plain source code, then package are folder, but they can also be packaged (no pun intended) in a jar. you can open a jar as a zip, and you will se a manifest file, and thepackage structure.
Also there ase some standard class in their own package in the visrtual machine, and they are all the standard library
My question is this is there a way to put all the Java Imports in a jar file, so when you make a Java Program no need to import the files individually????
EDIT:
I mean like
import java.awt.*;
import java.awt.event.*;
into a jar file where u don't need to type out the import java.awt.*; everytime
You can use netbeans to do that http://java.sun.com/developer/technicalArticles/java_warehouse/single_jar/
If you're thinking of something like a C/C++ global include file that allows a single import statement at the top of files -- then no.
However, your Java IDE should be capable of adding imports for you automatically.
You are mixing two things - Java packages and jar files.
A package is not much more than a name space for classes often used together. The import java.awt.* statement does not add the AWT classes to your program, it just lets you write Graphics instead of java.awt.Graphics and similar. There is nothing you can do to avoid importing them, if you don't want to spell them out (which is even more annoying).
To be able to use a class at runtime, this class has to be available to the virtual machine - independently whether you imported it or wrote its name fully. The standard classes like java.awt.* are usually already known to your VM (since they are part of the runtime environment). To use other classes (including your own ones), you need to include them to the class path (e.g. by the -cp argument to the java command, or by putting them in the current directory), or you need to load them by an own classloader. Here you can use jar files - the class files can either be in jar files mentioned in the class path, or be inside of directories mentioned in the class path. (The URLClassloader works the same way.)
But again, packaging classes in jars does not avoid importing them to be able to use them. One of them concerns the compiler's name resolution, the other concerns the runtime class loading.
Suppose somewhere I import javax.servlet.http.HttpServlet.
My questions:
Does this mean: I could find a folder structure like javax/servlet/http somewhere and inside that HttpServlet.class file would be present?
If not, where exactly this class file could be found?
Does this mean: These are just nested namespaces with no relevance to folder structures?
Package name in the above mentioned import would be javax.servlet or javax.servlet.http? Probably both are packages and first one is super package of the later one?
How is this class file actually included? I've read import is not like c/c++ include.
Thanks.
yes
see 1.
see 1.
package name is javax.servlet.http
The classloader will locate the class (from its classpath) at runtime
Yes
It could also be in a jar file (in the javax/servlet/http directory)
No (see 1.)
More precisely, it's the parent package
Imports gives access to classes external to the file being compiled. The .class file contains references to the external classes it needs. Constants (final static variables) can be inlined (their values are inserted by the compiler in the code that use them).
1 - Does this mean: I could find a folder structure like javax/servlet/http somewhere and inside that HttpServlet.class file would be present?
In this case, probably not in the file system, per se. (This class is part of the J2SE runtime libraries.)
2 - If not, where exactly this class file could be found?
In a JAR file that is on your JVM's classpath or bootclasspath. The JAR file is an archive containing .class files and other resources. The pathname of the class within the JAR file would be /javax/servlet/http/HttpServlet.class. (In this case the class in the rt.jar file.)
3 - Does this mean: These are just nested namespaces with no relevance to folder structures?
No. If you have file system folders on your classpath, they may be searched to find classes, before or after JAR files, depending on where on the classpath they are. The classpath effectively overlays the namespaces. Namespaces of JAR files can overlay namespaces of file system folders, and vice versa, depending on the effective classpath.
4 - Package name in the above mentioned import would be javax.servlet or javax.servlet.http?
javax.servlet.http
4 continued - Probably both are packages and first one is super package of the later one?
Both are packages, but there is no such thing as a "super package" in Java. As far as the Java language is concerned javax.servlet and javax.servlet.http are unrelated packages. Some people might say that javax.servlet is the parent package of javax.servlet.http, but this statement has no intrinsic meaning from the perspective of the Java language. The apparent parent-child relationship is purely conventional.
5 - How is this class file actually included? I've read import is not like C/C++ include.
The class file is not "included" in any sense. A Java import is little more than a shorthand that allows you to refer to the imported name without qualifying it with its full package name.
Does this mean: I could find a folder
structure like javax/servlet/http
somewhere and inside that
HttpServlet.class file would be
present?
Yes (most likely packaged inside a jar file)
Package name in the above mentioned import would be
javax.servlet or javax.servlet.http?
Probably both are packages and first
one is super package of the later one?
Yes again
How is this class file actually
included? I've read import is not like
c/c++ include.
import packagename.classname and must be before class declaration ex:
import javax.servlet.http.HttpServlet;
A fully qualified classname consists of one package name (the namespace) and the classname. Let's take a simple example:
java.lang.Object
The (simple) classname is Object, the packagename is java.lang. There is a practical recommendation in the JLS to construct a packagename with identifiers separated by dots. This is practical because this way we can map a packagename to a folder structure. The packagename from the above example is mapped to ./java/lang, the fully qualified classname to a file ./java/lang/Object.class for the binary and ./java/lang/Object.java for the source file.
This makes it pretty easy for a classloader to find classfiles on the filesystem. The classloader simply evaluates the namespace (packagename) for the folder and the simple classname for the name of the classfile.
A common misunderstanding is thinking, packagenames are somewhat hierarchical. This is not true. There is no relation between packages com.example.bean and com.example.bean.impl. The first one is not a sort of parent package.
For a slightly higher-level answer: the package name is a way of creating a namespace - there is no hierarchy of namespaces. However, the actual class (using the fully-qualified name, e.g. javax.servlet.http.HttpServlet) needs to be loaded by a ClassLoader.
The bog-standard ClassLoader that is used by the JVM is an instance of java.net.URLClassLoader (well, a subclass). This can look up classes given a starting point of either a directory or a JAR file. The package name is the overlaid over the filesystem structure to get the location of the class.
There are other ClassLoaders out there - most also follow this convention to some degree, but it is just a convention. ClassLoaders can load classes however they choose, including dynamically generating them.
For javax.servlet.http.HttpServlet, you'll probably find the class file inside a jar called something like servlet.jar or j2ee.jar. There's a neat utility called JFind that will help you locate where a class can be found - it's also usually pretty easy within an IDE as well.
For question 5 - as others have mentioned, the import statement simply brings the imported class or package into the local namespace, allowing you to use the convenient short name of HttpServlet instead of using the long name of javax.servlet.http.HttpServlet everytime you need to refer to it. You can program in Java and never use an import statement if you like, though people will probably look at you oddly.
For instance
import org.apache.nutch.plugin.Extension,
though used many times,
I've no much idea what is done essentially.
EDIT: Is org.apache.nutch.plugin essentially 4 directories or fewer than 4 like a directory named org.apache?
I think the question you might be trying to ask is, "What are packages in Java, and how does the import keyword relate to them?". Your confusion about directory structures might stem from the fact that some other languages have include directives that use file names to literally include the contents of the specified file in your source code at compile time. C/C++ are examples of languages that use this type of include directive. Java's import keyword does not work this way. As others have said, the import keyword is simply a shorthand way to reference one or more classes in a package. The real work is done by the Java Virtual Machine's class loader (details below).
Let's start with the definition of a "Java package", as described in the Wikipedia article:
A Java package is a mechanism for
organizing Java classes into
namespaces similar to the modules of
Modula. Java packages can be stored in
compressed files called JAR files,
allowing classes to download faster as
a group rather than one at a time.
Programmers also typically use
packages to organize classes belonging
to the same category or providing
similar functionality.
In Java, source code files for classes are in fact organized by directories, but the method by which the Java Virtual Machine (JVM) locates the classes is different from languages like C/C++.
Suppose in your source code you have a package named "com.foo.bar", and within that package you have a class named "MyClass". At compile time, the location of that class's source code in the file system must be {source}/com/foo/bar/MyClass.java, where {source} is the root of the source tree you are compiling.
One difference between Java and languages like C/C++ is the concept of a class loader. In fact, the concept of a class loader is a key part of the Java Virtual Machine's architecture. The job of the class loader is to locate and load any class files your program needs. The "primordial" or "default" Java class loader is usually provided by the JVM. It is a regular class of type ClassLoader, and contains a method called loadClass() with the following definition:
// Loads the class with the specified name.
// Example: loadClass("org.apache.nutch.plugin.Extension")
Class loadClass(String name)
This loadClass() method will attempt to locate the class file for the class with given name, and it produces a Class object which has a newInstance() method capable of instantiating the class.
Where does the class loader search for the class file? In the JVM's class path. The class path is simply a list of locations where class files can be found. These locations can be directories containing class files. It can even contain jar files, which can themselves contain even more class files. The default class loader is capable of looking inside these jar files to search for class files. As a side note, you could implement your own class loader to, for example, allow network locations (or any other location) to be searched for class files.
So, now we know that whether or not "com.foo.bar.MyClass" is in a class file in your own source tree or a class file inside a jar file somewhere in your class path, the class loader will find it for you, if it exists. If it does not exist, you will get a ClassNotFoundException.
And now to address the import keyword: I will reference the following example:
import com.foo.bar.MyClass;
...
public void someFunction() {
MyClass obj1 = new MyClass();
org.blah.MyClass obj2 = new org.blah.MyClass("some string argument");
}
The first line is simply a way to tell the compiler "Whenever you see a variable declared simply as type MyClass, assume I mean com.foo.bar.MyClass. That is what's happening in the case of obj1. In the case of obj2, you are explicitly telling the compiler "I don't want the class com.foo.bar.MyClass, I actually want org.blah.MyClass". So the import keyword is just a simple way of cutting down on the amount of typing programmers have to do in order to use other classes. All of the interesting stuff is done in the JVM's class loader.
For more information about exactly what the class loader does, I recommend reading an article called The Basics of Java Class Loaders
All it's doing is saving you typing. Instead of having to type "org.apache.nutch.plugin.Extension" every time you want to use it, the import allows you to refer to it by its short name, "Extension".
Don't be confused by the word "import" - it's not loading the .class file or anything like that. The class loader will search for it on the CLASSPATH and load it into perm space the first time your code requires it.
UPDATE: As a developer you have to know that packages are associated with directories. If you create a package "com.foo.bar.baz" in your .java file, it'll have to be stored in a directory com/foo/bar/baz.
But when you download a JAR file, like that Apache Nutch library, there are no directories involved from your point of view. The person who created the JAR had to zip up the proper directory structure, which you can see as the path to the .class file if you open the JAR using WinZip. You just have to put that JAR in the CLASSPATH for your app when you compile and run.
Imports are just hints to the compiler telling him how to figure out the full name of classes.
So if you have "import java.util.*;" and in your code you are doing something like "new ArrayList()", when the compiler processes this expression it first needs to find the fully qualified name of the type ArrayList. It does so by going thru the list of imports and appending ArrayList to each import. Specifically, when it appends ArrayList to java.util it get the FQN java.util.ArrayList. It then looks up this FQN in its class-path. If it finds a class with such a name then it knows that java.util.ArrayList is the correct name.
is "org.apache.nutch.plugin" essentially 4 directories?
If you have a class whose name is org.apache.nutch.plugin.Extension, then it is stored somewhere in the classpath as a file org/apache/nutch/plugin/Extension.class. So the root directory contains four nested subdirectories ("org", "apache", "nutch", "plugin") which in turn contain the class file.
import org.apache.nutch.plugin.Extension is a compilation time shortcut that allows you to refer to the Extension class without using the class' fully qualified name. It has no meaning at runtime, it's only a compilation time trick to save typing.
By convention the .class file for this class will be located in folder org/apache/nutch/plugin either in the file system or in a jar file, either of which need to be in your classpath, both at compile time and runtime. If the .class file is in a jar file then that jar file needs to be in your classpath. If the .class file is in a folder, then the folder that is the parent of folder "org" needs to be in your classpath. For example, if the class was located in folder c:\myproject\bin\org\apache\nutch\plugin then folder c:\myproject\bin would need to be part of the classpath.
If you're interested in finding out where the class was loaded from when you run your program, use the -verbose:class java command line option. It should tell you which folder or jar file the JVM found the class.
Basically when you make a class you can declare it to be part of a package. I personally don't have much experience with doing packages. However, afaik, that basically means that you are importing the Extension class from the org.apache.nutch.plugin package.
Buliding off of Thomas' answer, org.apache.nutch.plugin is a path to the class file(s) you want to import. I'm not sure about this particular package, but generally you'll have a .jar file that you add to your classpath, and your import statement points to the directory "./[classpath]/[jarfile]/org/apache/nutch/plugin"
you can't have a directory named org.apache as a package. the compiler won't understand that name and will look for the directory structure org/apache when you import any class from that package.
also, do not mistake the Java import statement with the C #include preprocessor instruction. the import statement is, like they've said, a shorthand for you to type fewer characters when referring to a class name.