Java Class Loaders: Dynamic Loading and Linking of Classes, Study notes of Applications of Computer Sciences

An overview of java class loaders, their intent, and the process of load-time and run-time dynamic loading and linking. It covers the java api for class loading and the different types of built-in class loaders. Students will learn how classes are loaded and linked in java, and the role of class loaders in the java class hierarchy.

Typology: Study notes

2016/2017

Uploaded on 10/06/2017

suresh-kamble
suresh-kamble 🇮🇳

5

(2)

8 documents

1 / 4

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
BFH/HTA Biel/DUE/Course 355/ Software Engineering 2
Dynamic Java Class Loaders 1
Class Loaders
Intent
Class loaders let Java dynamically load classes (and linking) on demand, at run-
time. Applications may use predefined class loaders, or, if they must rely on spe-
cific behavior, may construct their specific class loaders.
Note. Class loaders are tightly coupled with security issues. Security, however,
will not be discussed here, and is deferred to the course “Advanced Java Technol-
ogies”.
Load-Time Dynamic Loading and Linking
Consider the following program:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
BFH/HTA Biel/DUE/Course 355/ Software Engineering 2
Dynamic Java Class Loaders 2
When the JVM loads class Hello, it notices that this class uses classes String
and System, and extends class Object. If the JVM has not yet loaded one of
those classes by this point, the JVM must run off and load these ones before it
can finish loading Hello.
Run-Time Dynamic Loading and Linking
Run-time dynamic loading and linking loads a class file and resolves its names
until run-time, when the name of the class has been determined:
public class X implements Runnable {
public void run() {
System.out.println("Class X.");
}
}
public class Y implements Runnable {
public void run() {
System.out.println("Class Y.");
}
}
BFH/HTA Biel/DUE/Course 355/ Software Engineering 2
Dynamic Java Class Loaders 3
public class LoadAndExecute {
public static void main(String[] args) { // w/o arg checking
Class cl = Class.forName(args[0]);
Object o = cl.newInstance();
Runnable r = (Runnable) o;// assuming a Runnable
r.run();
} }
Remarks:
Variable cl holds a class object (an instance of class Class).
Class.forName(String) loads and links a class file at the point of its use,
given the fully qualified class name.
Method newInstance creates an instance of the class the corresponding
class object stands for.
If you know the type of the object (here Runnable) then you can downcast to
the known type and apply corresponding methods on it.
If you don’t know the type then you can use reflection on the class object to
obtain more information about the supported methods, etc.
BFH/HTA Biel/DUE/Course 355/ Software Engineering 2
Dynamic Java Class Loaders 4
Class Loaders
Java uses class loaders for the loading and linking classes. Class loaders are
ordinary Java objects of subclasses of class java.lang.ClassLoader, except
the bootstrap class loader. By default, Java application typically has the following
class loaders:
Bootstrap class loader: native code, used for loading the classes belonging
to the Java system. That is, packages such as java.*,javax.*,
org.omg.*, etc.
The class loader for the extensions: e.g. class sun.misc.Launcher$-
ExtClassLoader, used for loading classes or JAR files added to JRE’s
lib/ext directory. Some JVMs combine this one with the one above.
The application class loader: e.g. class sun.misc.Launcher$-
AppClassLoader, used for loading the classes for the application. The
classes are searched within the file system relative to the definition of the
CLASSPATH variable.
In addition, an application may install one or more custom class loaders, e.g.
MyClassLoader.
An applet uses an applet class loader to load applet code relative to a URL.
pf3
pf4

Partial preview of the text

Download Java Class Loaders: Dynamic Loading and Linking of Classes and more Study notes Applications of Computer Sciences in PDF only on Docsity!

BFH/HTA Biel/DUE/Course 355/

Software Engineering 2

Dynamic Java

Class Loaders

1

Class Loaders

Intent

Class loaders let Java dynamically load classes (and linking) on demand, at run-time. Applications may use predefined class loaders, or, if they must rely on spe-cific behavior, may construct their specific class loaders. Note.

Class loaders are tightly coupled with security issues. Security, however,

will not be discussed here, and is deferred to the course “Advanced Java Technol-ogies”.

Load-Time Dynamic Loading and Linking

Consider the following program:

public class

Hello

public static

void

main(

String

[]

args)

System

.out.println("Hello,

world!");

BFH/HTA Biel/DUE/Course 355/

Software Engineering 2

Dynamic Java

Class Loaders

2

When the JVM loads class

Hello

, it notices that this class uses classes

String

and

System

, and extends class

Object

. If the JVM has not yet loaded one of

those classes by this point, the JVM must run off and load these ones before itcan finish loading

Hello

Run-Time Dynamic Loading and Linking

Run-time dynamic loading and linking loads a class file and resolves its namesuntil run-time, when the name of the class has been determined:

public class

X

implements

Runnable

public void

run()

System.out.println("Class

X.");

} public class

Y

implements

Runnable

public void

run()

System.out.println("Class

Y.");

BFH/HTA Biel/DUE/Course 355/

Software Engineering

Dynamic Java

Class Loaders

public class

LoadAndExecute

public static void main(String[] args) { // w/o arg checking

Class cl =

Class.forName

(args[0]);

Object o =

cl.newInstance

Runnable r =

(Runnable) o

;// assuming a Runnable

r.run();

Remarks:•^

Variable

cl

holds a class object (an instance of class

Class

•^

Class.forName(String)

loads and links a class file at the point of its use,

given the fully qualified class name.

-^

Method

newInstance

creates an instance of the class the corresponding

class object stands for.

-^

If you know the type of the object (here

Runnable

) then you can downcast to

the known type and apply corresponding methods on it.

-^

If you don’t know the type then you can use

reflection

on the class object to

obtain more information about the supported methods, etc.

BFH/HTA Biel/DUE/Course 355/

Software Engineering

Dynamic Java

Class Loaders

Class Loaders

Java uses

class loaders

for the loading and linking classes. Class loaders are

ordinary Java objects of subclasses of class

java.lang.ClassLoader

, except

the bootstrap class loader. By default, Java application typically has the followingclass loaders:•^

Bootstrap class loader:

native code

, used for loading the classes belonging

to the Java system. That is, packages such as

java.*

,^

javax.*

org.omg.*

, etc.

•^

The class loader for the extensions:

e.g. class

sun.misc.Launcher$-

ExtClassLoader

, used for loading classes or JAR files added to JRE’s

lib/ext

directory. Some JVMs combine this one with the one above.

•^

The application class loader:

e.g. class

sun.misc.Launcher$-

AppClassLoader

, used for loading the classes for the application. The

classes are searched within the file system relative to the definition of the CLASSPATH

variable.

In addition, an application may install one or more custom class loaders, e.g. MyClassLoader

An applet uses an applet class loader to load applet code relative to a URL.

BFH/HTA Biel/DUE/Course 355/

Software Engineering 2

Dynamic Java

Class Loaders

5

The Java 2 Parent Class Loader Delegation Model

By convention, when a class loader is asked to load a class, it

first

asks the class

loader that loaded

it

(!) to load that class. I.e. the following delegation model

exists:

When Not Using the Parent Delegation Model

bootstr^ In some circumstances, you do not want to use the default delegation model. Forexample, the Apache/Tomcat servlet engine uses class loaders that try to loadthe requested class directly (and not delegating it to the parent class loader).Be careful when writing class loaders not using the parent class loader delegationmodel.

ap

:ExtClassLoader

:AppClassLoader

:MyClassLoader

BFH/HTA Biel/DUE/Course 355/

Software Engineering 2

Dynamic Java

Class Loaders

6

The java.lang.ClassLoader API

The public API:•^

The public API: getParent

returns the parent class loader.

getResource

getResourceAsStream

,^ getResources

return a single resource as an

input stream, or an enumeration of all resources.

getSystemClassLoader

getSystemResource

,^ getSystemResourceAsStream

getSystemResources

return the system versions of above. Finally,

loadClass

is used to load and link Java classes. Given a class loader

instance, you load a class for example (w/o exception handling): ClassLoader cl

Class c =

cl.loadClass

("example.Hello");

By default,

loadClass

performs the following steps:

  • calls

findLoadedClass()

to check if the class has already been loaded

  • calls

loadClass()

on the parent (if any)

  • calls

findClass(String)

to find the class.

Notice that

loadClass

is a template method.

BFH/HTA Biel/DUE/Course 355/

Software Engineering

Dynamic Java

Class Loaders

•^

The factory method API: findClass

,^

findLibrary

,^ findResource

, and

findResources

are fac-

tory methods. These will have to be overridden by subclasses.

-^

The base API: defineClass

provides a convenience method for translating a bytecode array

to a class object, performing all the loading, linking, and initialization. Othermethods are here, too, plus another

loadClass

method for internal use.

Important note: ^

A class always remembers the class loader that loaded it, and anyclasses referenced by that class that haven’t been loaded will be loaded(if possibly) by that class loader (however, by respecting the delegationmodel).

Java Name Spaces, Protection Domains, and Code Sources

This is an advanced topic. Will be discussed in course “Advanced Java Technolo-gies”.

BFH/HTA Biel/DUE/Course 355/

Software Engineering

Dynamic Java

Class Loaders

Java’s Built-In Class Loaders

java.security.SecureClassLoader

Intended to be the base class for all custom class loaders. When writing yourown class loader, either extend from class

URLClassLoader

(see next) or

from this class. java.net.URLClassLoader

Flexible class loader that uses URLs for loading classes. Since there are

file

URLs,

http

URLs, and

ftp

URLs, this class loader can load classes from the

file system, from HTTP servers, and from FTP servers.To load a class from a file: //

w/o exception handling

URL[] urls = { new File("

some_path

").toURL() };

ClassLoader cl = new URLCassLoader(urls);Object o = cl.loadClass("example.Hello").newInstance();

BFH/HTA Biel/DUE/Course 355/

Software Engineering 2

Dynamic Java

Class Loaders

13

Finally, you provide your custom

findClass

method. This method should use

one of the three forms of the

defineClass

methods defined in the

SecureClassLoader

class or its ancestors. Here, the simplest on is used:

protected

Class

findClass

(String

name)

throws

ClassNotFoundException

...byte[]

bytecode

retrieveClass(className);

return

defineClass

(name,

bytecode,

bytecode.length);

} private byte[]

retrieveClass

(String classname)

// perhaps

add

"throws"-clause

here

// Get

byte

array

of

the

class.

Add methods for obtaining resources if necessary. No code examples shown.