Understanding class.Forname (2)

xiaoxiao2021-03-06  151

The Launcher constructor, after constructing both the ExtClassLoader and AppClassLoader, sets the thread context ClassLoader to be the AppClassLoader instance. This means, unless your code (or other code loaded by your application) changes it, the thread's context ClassLoader is the AppClassLoader instance. This Also Means That Now The AppClassLoader Instance Is Available To Extension Classes:

Import java.lang.reflect. *;

Public Class fixeddyNamiCloader

{

Public static void main (string [] args)

Throws Exception

{

// INSTEAD OF

// Class

Torun

= Class.Forname (Args [0]);

// USE:

Thread t = thread.currentthread ();

ClassLoader Cl = T. GetContextClassLoader ();

Class

Torun

= cl.loadclass (args [0]);

String [] newargs = scrubargs (args);

Method mainmethod = findmain

Torun

);

Mainmethod.invoke (null, new object [] {new mark});

}

Private static string [] Scrubargs (String [] ARGS)

{

String [] Toreturn = New string [args.length-1];

For (int i = 1; i

{

ToreTurn [I-1] = args [i] .tolowercase ();

}

Return ToreTurn;

}

Private Static Method Findmain (Class Clazz)

Throws Exception

{

Method [] methods = Clazz.getMethods ();

For (int i = 0; i

{

IF (Methods [i] .GetName (). Equals ("main")))

Return Methods [i];

}

Return NULL;

}

}

After Compiling, Placing Into a .jar and Dropping T. Jar Into The Extensions Directory, We achieve Success:

> Java FixeddyNamiAder Echo One Two Three

Echo arg0 = one

Echo arg1 = two

Echo arg2 = three

.

Those readers familiar with multi-threaded environments may be wondering about Threads created by user-code-what ClassLoader is set to be the context ClassLoader for user-created Threads? A Thread, when created, inherits the context ClassLoader of the Thread that created it , so all Threads, unless modified, will have AppClassLoader set as their context ClassLoader. Use the 3-arg form of Class.forName. Sun introduced a new form of the forName method that takes 3 arguments, instead of just one. In addition to the name of the Class to load, callers pass a boolean parameter indicating whether to initialize the loaded Class or not, and a ClassLoader parameter to load the code through This method performs the same steps as the 1-arg Class.forName;. in fact , the 1-arg version of Class.forName calls directly into the 3-arg version, passing "true" and the caller's ClassLoader as the second and third parameters, respectively. Class.forName (classname, init_flag, classloader) will load the code "T HROUGH "The ClassLoader Passed to It; CRUDELY PUT, IT Functions Somewhat Similar To The Following: ClassName (String ClassNM, Boolean Init, ClassLoader Loader)

.

{

//.

Loader.loadClass (Classnm);

//.

}

. This is a gross oversimplification, but the point is clear-instead of using the caller's ClassLoader to do the load, it uses the ClassLoader instance passed in This now means, to avoid the problem that started this paper, FixedDynamicLoader could also do:

Public Class fixeddyNamiCloader

{

Public static void main (string [] args)

Throws Exception

{

// Class

Torun

= Class.Forname (Args [0]);

Class

Torun

=

Class.Forname (Args [0],

True,

ClassLoader.getsystemClassLoader ());

String [] new mark = scrubargs (args); method mainmethod = findmain

Torun

);

Mainmethod.invoke (null, new object [] {new mark});

}

//.

}

This code has the advantage of being perhaps a bit more explicit about what the intent of the code is, as opposed to the slightly more obscure use of the Thread's context ClassLoader. Other (technical) differences between the two are more profound, however. Class .forName vs ClassLoader.loadClass. There are some subtle differences between these two APIs. The method call CL.loadClass (C), where CL is our ClassLoader and C is the name of the class to load, queries the ClassLoader directly for the class by name. This in turn relies on ClassLoader delegation to ask the bootstrap ClassLoader to determine if the class has already been loaded. Conversely, the method call Class.forName (C, false, CL) uses the VM's internal class resolution mechanism to do the . actual loading Among other things, this allows Class.forName to support the loading of arrays of Classes as a type; for example, calling CL.loadClass ( "[C;") will result in failure, where doing the same with Class. Forname ("[C;", False, Cl) W Ill succeed.

Consequences

As with any discussion, there are consequences to each of the solutions set forth within this white paper Versioning:. The 3-arg Class.forName, Thread.getContextClassLoader, and Thread.setContextClassLoader are Java2 / JDK1.2 APIs This means any Java. API or class library that wants to remain compatible or usable with JDK 1.1 will not be able to be loaded. Remember, the VM, during its resolution step of classloading (see [4]), will verify that all methods referenced inside of a class actually exist, and will throw an Exception if this is not the case. How, then can code avoid this ClassLoader trap in Java2 code, while remaining compatible with 1.1 code? One solution is to eliminate your JDK 1.1 compatibility requirement. It sounds a bit draconian, but Java2 / JDK 1.2 has been out for approximately a year at the time of this writing, Java2 / JDK 1.3 is in the final beta stages. More to the point, almost no new development is being done in JDK 1.1 (except for Applets, Since 1.1 IS AS FAR AS MO st browsers have gone in JDK support). However, for many APIs and / or design teams, this is an unacceptable solution. Too many JDK 1.1-based systems exist to simply write off JDK 1.1 environments entirely, and developing a system that fails to work properly in a JDK 1.2 / Java2 environment is simply unthinkable. fortunately, a convenient middle ground is possible.Because Java uses a lazy dynamic-loading system (see [2], [4], or [5] for details), classes Aren't loaded Into The VM Until The Last Possible Moment. This Means It's Possible To Use A Strategy-Pattern Approach Towards ClassLoading, Based On The Version of The VM Your Code Is Executing WithNIN:

Package com.javageeks.lang.classloader;

Interface VmclassLoader

{

Public Class LoadClass (String CLS) throws ClassNotFoundException;

}

Public Class ClassLoaderHelper

TED NEWARD

14

{

Private static vmclassloader vmclassloader;

Static

{

String vmversion = system.getproperty ("java.version");

IF (VMVersion.startSwith ("1.2")))

{

//System.out.println ("Loading 1.2 VmclassLoader ");

VmclassLoader = New VmclassLoader ()

{

Public Class LoadClass (String CLS)

Throws ClassNotFoundException

{

Thread t = thread.currentthread ();

ClassLoader Cl = T. GetContextClassLoader ();

Return Cl.LoadClass (CLS);

}

}

}

Else IF (VMVersion.StartSwith ("1.1") ||

VMVERSION.STARTSWITH ("1.0"))

{

//System.out.println ("Loading 1.1 / 1.0 VmclassLoader ");

VmclassLoader = New VmclassLoader ()

{

Public Class LoadClass (String CLS)

Throws ClassNotFoundException

{

Return Class.Forname (CLS);

}

}

}

Else

{

//???

}

}

Public Static Class LoadClass (String CLS)

Throws ClassNotFoundException

{

Return VmclassLoader.loadClass (CLS);

}

/ **

* Test Driver.

* /

Public static void main (string [] args)

Throws Exception

{

// Class

Torun

= Class.Forname (Args [0]);

Class

Torun

=

ClassLoaderHelper.LoadClass (args [0]);

String [] newargs = scrubargs (args);

Java.lang.reflect.method mainmethod =

Findmain

Torun

);

Mainmethod.invoke (null, new object [] {new mark});

TED NEWARD

15

}

Private static string [] Scrubargs (String [] ARGS)

{

String [] Toreturn = New string [args.length-1];

For (int i = 1; i

{

ToreTurn [I-1] = args [i] .tolowercase ();

}

Return ToreTurn;

}

Private static java.lang.reflect.Method Findmain (Class Clazz)

Throws Exception

{

Java.lang.reflect.method [] methods = CLAZZ.GETMETMETHODS (); for (int i = 0; i

{

IF (Methods [i] .GetName (). Equals ("main")))

Return Methods [i];

}

Return NULL;

}

}

The key here is in the static block of the ClassLoaderHelper class. When loaded in a 1.2 VM, an anonymous instance of VMClassLoader is created, which uses the Thread contextClassLoader methods to obtain the ClassLoader and call loadClass. When loaded into a 1.1 (or 1.0 Although this is, assebclassloader instance falps back on classloader instance falps back on class .forname, Since 1.1 VMS Don't Have The Problem Described in this Paper.

Running this code within a 1.2 VM Yields The Following:

> java -version

Java Version "1.2"

Classic VM (Build JDK-1.2-V, Native Threads)

> Java ClassLoaderHelper Echo One Two Three

Loading 1.2 VmclassLoader

Echo arg0 = one

Echo arg1 = two

Echo arg2 = three

Running this code within a 1.1 VM Yields the Following:

> java -version

Java Version "1.1.7"

> Java ClassLoaderHelper Echo One Two Three

Loading 1.1 / 1.0 VmclassLoader

Echo arg0 = one

Echo arg1 = two

Echo arg2 = three

By using ClassLoaderHelper.loadClass instead of Class.forName, code can continue to support both JDK 1.1 and JDK 1.2 (and beyond) VMs without having to maintain two (or more) separate codebases. (ClassLoaderHelper could also be modified to use the 3- arg version of Class.forName instead of the Thread's context ClassLoader. However, it would require a ClassLoader instance to be passed in, to avoid making the assumption that it should use the system ClassLoader.) Using Thread.getContextClassLoader relies on the Thread's context

ClassLoader to be appropriately set. What if the Thread's current context ClassLoader is not the one expected, but is instead set by an arbitrary third-party package (like RMI or JNDI) In fact, there's not much you can do to prevent this. Because Thread.setContextClassLoader makes a Security check, however, you can take some small comfort in the fact that only those systems that have "setContextClassLoader" permission will be allowed to modify a Thread's context ClassLoader. Practically speaking, this means in an enterprise system, you can modify your policy file such that only your codebase is permitted to modify the Thread's context ClassLoader. This does not prevent Sun-sponsored APIs (like RMI, which is "part" of the runtime library, or JNDI, which is part of The Runtime Library Starting in JDK 1.3) from Being Able To Modify It, But at Least You Can Prevent Rogue Third-Parties from Doing So.

Knowing your loading ClassLoader In order to use the 3-arg form of Class.forName, callers must have the ClassLoader instance they want to load through available to them in order to pass it;. Under certain circumstances, simply calling ClassLoader.getSystemClassLoader () here will be wildly inappropriate. For example, a Servlet will usually be loaded under its own ClassLoader, and if the Servlet calls Class.forName with the system ClassLoader as the third argument, code loaded under the Servlet's ClassLoader will not be found. This situation can arise more commonly than one might expect-many servlets are bundled together with supporting code directly in the "servlets" directory, placing the supporting code under the Servlet ClassLoader's domain. Under those circumstances, using the Thread's context ClassLoader can be the only appropriate Parameter; You can Either Pass It as the third parameter to the 3-arg form of class.forname, or else call its loadingclass method Directly. But, as Pointed OU t in the aforementioned point, using it relies on the context ClassLoader being set correctly by the code that loaded your class. It may seem that callers will always know the ClassLoader they should call through. However, keep in mind that the ExtClassLoader / AppClassLoader pair is not the only situation in which ClassLoaders further "up the tree" are going to look to load code further "down" the ClassLoader tree. For example, sophisticated security mechanisms within a Java application might make use of an instance of URLClassLoader to load code ON a per-user-role basis;

certain parts of the application, however, will be constant, and therefore installed as an Extension. Those constant classes can not simply assume that the ClassLoader that loaded them will be the correct ClassLoader to pass into Class.forName (it won't-we ' re now right back to the original problem), nor will simply passing ClassLoader.getSystemClassLoader () be correct, either. Instead, they will have to trust that somebody will set the current Thread's context ClassLoader to be that custom URLClassLoader instance, and use that To Dynamically Load the code.summary

Java2, with the release of JDK 1.2, subtly changed the nature of classloading. When Sun added the "Extens ion" capability to the language / environment, they split the responsibility for loading Extensions code and "Application" (that is, CLASSPATH-based ) code into two separate ClassLoaders. Under "normal" circumstances, this change will be invisible to most Java developers, but those working under dynamic-loading systems need to be aware of this change and what it means for them. Many Java developers may believe that the circumstances described in this paper will not apply to them. "I'm not making use of any of this", they mutter to themselves. "Why do I care?" It's a more relevant concern than readers might wish. Several key Java technologies, most notably RMI and JNDI, make use of the Thread context ClassLoaders for precisely this reason-the core classes for both technologies are loaded high up in the CllassLoader tree, but need to be able to load code stored along the CLASSPATH. Worse Y et, as more enterprise systems are built under EJB servers, which may well be installed as Extensions, this problem could become more and more common. As Java2 Security becomes more and more well-understood and implemented in Java projects, this issue will again rear its ugly head, since developers will slowly begin to adopt codebase permissions on a per-ClassLoader basis. Multiple ClassLoaders means the potential for code further up the chain looking for code further down the chain, and we're right back to where we started with ALL THIS.

Fortunately, as JDK 1.1 systems slowly phase out, it should become more and more comfortable to use Thread.currentThread () getContextClassLoader () loadClass () or the 3-arg version of Class.forName () directly;.. Until that time; However, The ClassLoader Helper Class Should Provide A Measure of Portability Across JVM Versions For Doing Dynamic ClassLoading from With Extension.bibliography / Additional

Reading

[1] JDK 1.2 Documentation Bundle. See http://www.javasoft.com for downloading.

[2] << Liang / Bracha Oopsla Paper >>

[3] Java Language Specification.

[4] Java Virtual Machine Specification, 2nd Edition.

[5] Server-Side Java, by TED NEWARD. Manning Publishing, Feb 2000.

[6] Personal Communication with Peter Jones of Sun Microsystems; Used with permission.

Copyright

This Paper, And Accompanying Source Code, IS CopyRight © 2000 by TED NEWARD. All Rights Reserved. Usage for any other Purpose

Than Personal or Non-Commercial Education IS Expressly Prohibited WITHOUT WRITTEN Consent. Code Is Copywritten Under The Lesser

GNU Public License (LGPL). For Questions OR Concerns, Contact Author.

转载请注明原文地址:https://www.9cbs.com/read-128042.html

New Post(0)