Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved  |  Confidential ClassLoader  개요 강 명 철 2006.11 Core Java
Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved  |  Confidential 목차 <ul><li>Class Loader </li></ul><ul><li>Custo...
<ul><li>ClassLoader </li></ul>1. JVM Architecture
<ul><li>ClassLoader </li></ul><ul><li>Class loading takes place in two phases : </li></ul><ul><ul><li>Loading </li></ul></...
3. Class Class in Java <ul><li>ClassLoader </li></ul><ul><li>Instances of class java.lang.Class </li></ul><ul><li>   repr...
4. Class Loading <ul><li>ClassLoader </li></ul><ul><li>When you define a class, say Foo, and initiate it ( to create its i...
5. Class Loaders in JVM <ul><li>ClassLoader </li></ul><ul><li>Every JVM has two types of class loaders </li></ul><ul><ul><...
6. Class Loaders Rules <ul><li>ClassLoader </li></ul><ul><li>Consistency Rule </li></ul><ul><ul><li>Class loaders never lo...
6. Visibility  <ul><li>ClassLoader </li></ul>
6. Visibility  실습 <ul><li>ClassLoader </li></ul><ul><li>Java Statics </li></ul>public class Dummy { public static int stat...
6. Visibility  실습 <ul><li>ClassLoader </li></ul><ul><li>Java Statics </li></ul>public class Dummy { public static int stat...
7. Delegation Model <ul><li>ClassLoader </li></ul>class NetworkClassLoader extends ClassLoader { String host; int port; pu...
7. Delegation Model <ul><li>ClassLoader </li></ul>
7. Delegation Model  실습 <ul><li>ClassLoader </li></ul><ul><li>Java 1.1 Style </li></ul>public class TestClassLoader extend...
7. Delegation Model  실습 <ul><li>ClassLoader </li></ul><ul><li>Java 1.2 Style </li></ul>public class TestClassLoader extend...
//java.lanag.ClassLoader  일부 protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundExce...
8. Standard Class Loader <ul><li>ClassLoader </li></ul><ul><li>Standard ClassLoader </li></ul>
8. Standard Class Loader <ul><li>ClassLoader </li></ul><ul><li>Java Options </li></ul>
 
public class ClassLoaderTree { public static void printClassLoaderTree(ClassLoader l) { if(l== null){ System.out.println(&...
<ul><li>java -classpath ./bin ClassLoaderTree </li></ul><ul><li>java -Djava.ext.dirs=./bin ClassLoaderTree </li></ul><ul><...
<ul><li>What is a class loader? </li></ul><ul><ul><li>mechanism for loading classes into the JVM </li></ul></ul><ul><ul><l...
<ul><li>Unidirectional   visibility </li></ul><ul><ul><li>Parent-loaded classes cannot see child-loaded classes </li></ul>...
<ul><li>Bootstrap ClassLoader </li></ul><ul><ul><li>aka Primordial ClassLoader </li></ul></ul><ul><ul><li>Created by the J...
<ul><li>Determine   Initial ClassLoader </li></ul><ul><li>Delegate to Parent ClassLoader </li></ul><ul><li>Class Loaded? <...
Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved  |  Confidential 목차 <ul><li>Class Loader </li></ul><ul><li>Custo...
1. Java  내부의  ClassLoader <ul><li>Custom ClassLoader </li></ul><ul><li>java.security.SecureClassLoader </li></ul><ul><ul><...
public static void main(String[] args) throws Exception { URL[] urlArray = { //new java.io.File(&quot;subdir.jar&quot;).to...
public static void main(String[] args) throws Exception { URL[] urlArray = { new URL(&quot;http&quot;, &quot;www.javageeks...
public static void main(String[] args) throws Exception { URL[] urlArray = { new URL(&quot;ftp&quot;, &quot;reader:passwor...
2. Why write a ClassLoader ? <ul><li>Custom ClassLoader </li></ul><ul><li>The default ClassLoader only knows how to load c...
3. Class Loader  확장 <ul><li>Custom ClassLoader </li></ul><ul><li>findClass(…) </li></ul><ul><ul><li>Class  이름으로 부터  Byte C...
4. Class Loader  실습 <ul><li>Custom ClassLoader </li></ul><ul><li>FileSystemClassLoader </li></ul><ul><ul><li>Local File Sy...
4. Class Loader  실습 <ul><li>Custom ClassLoader </li></ul><ul><li>CompilingClassLoader </li></ul><ul><ul><li>When a class i...
4. Class Loader  실습 <ul><li>Custom ClassLoader </li></ul><ul><li>HotDeploy </li></ul>java -classpath ./bin athena.loader.P...
4. Class Loader  실습 <ul><li>Custom ClassLoader </li></ul><ul><li>Context Class Loader </li></ul>java -classpath ./bin Dyna...
Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved  |  Confidential 목차 <ul><li>Class Loader </li></ul><ul><li>Custo...
1. Class Not Found <ul><li>Diagnosing </li></ul><ul><li>ClassNotFoundException  </li></ul><ul><ul><li>Used String represen...
<ul><li>ClassCastException </li></ul><ul><ul><li>same Class was loaded by two different ClassLoaders </li></ul></ul><ul><l...
<ul><li>Place diagnostic statements in the application code </li></ul><ul><li>Place diagnostic statements in a custom Clas...
import java.io.File; import java.net.MalformedURLException; import java.net.URLClassLoader; import java.net.URL; import de...
package demo; public class Rabbit { } Rabbit.java rabbit.jar C:> jar tf rabbit.jar demo/ demo.Rabbit.class   C:> javac –cl...
<ul><li>TopHat should instantiate and display a String  </li></ul><ul><li>representation of a Rabbit, even though </li></u...
// Create a ClassLoader that knows where to find demo. Rabbit URL rabbitURL = new File(&quot;rabbit.jar&quot;).toURL(); UR...
C:>java TopHat ---> ClassLoader for TopHat: sun.misc.Launcher$AppClassLoader@e80a59 ---> Before setting a custom ContextCl...
protected Class findClass(final String name) throws ClassNotFoundException { try { return (Class)   AccessController.doPri...
protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class c = findLoadedC...
---> JVM is requesting that sun.misc.Launcher$AppClassLoader@e80a59 load demo.Rabbit --->  sun.misc.Launcher$AppClassLoade...
<ul><li>Regardless of how the Context ClassLoader is set , the classloader that loaded the calling Class will  always  be ...
ClassLoader loader = Thread.currentThread().getContextClassLoader(); loader.loadClass(“demo.Rabbit”).newInstance(); ClassL...
--->  [email_address]  is asking parent (sun.misc.Launcher$AppClassL oader@e80a59) to try to load demo.Rabbit. --->  sun.m...
감사합니다 . Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved  |  Confidential 대표전화 : +82-2-6484-0930 E-mail: chris_le...
Upcoming SlideShare
Loading in …5
×

Class loader basic

2,643 views

Published on

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,643
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
148
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Class loader basic

  1. 1. Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved | Confidential ClassLoader 개요 강 명 철 2006.11 Core Java
  2. 2. Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved | Confidential 목차 <ul><li>Class Loader </li></ul><ul><li>Custom Class Loader </li></ul><ul><li>Diagnosing </li></ul>
  3. 3. <ul><li>ClassLoader </li></ul>1. JVM Architecture
  4. 4. <ul><li>ClassLoader </li></ul><ul><li>Class loading takes place in two phases : </li></ul><ul><ul><li>Loading </li></ul></ul><ul><ul><li>Linking or resolution </li></ul></ul>2. How Classes are Loaded ?
  5. 5. 3. Class Class in Java <ul><li>ClassLoader </li></ul><ul><li>Instances of class java.lang.Class </li></ul><ul><li> represent classes and interfaces in a running Java application </li></ul><ul><li>Class has no public constructors </li></ul><ul><ul><li>Any applications cannot instantiate it </li></ul></ul><ul><ul><li>Class is automatically instantiated by JVM/class loader, when a class loading process is done </li></ul></ul><ul><li>Each instance of Class keeps a reference to a class loader that created it </li></ul>
  6. 6. 4. Class Loading <ul><li>ClassLoader </li></ul><ul><li>When you define a class, say Foo, and initiate it ( to create its instance) </li></ul><ul><li> i.e. when you execute new Foo(); </li></ul><ul><li>A local JVM (class loader) tries to </li></ul><ul><ul><li>Obtain the class definition of Foo </li></ul></ul><ul><ul><ul><li>Given the name of a class (i.e. Foo), the class loader locates a binary representation of Foo’s class definition </li></ul></ul></ul><ul><ul><ul><ul><li>Typically, it transforms the class name into a file name, and reads a class file of that name (e.g. Foo.class) from the local file system </li></ul></ul></ul></ul><ul><ul><ul><ul><li>If this step fails, JVM return a ClassDefNotFound exception </li></ul></ul></ul></ul><ul><ul><ul><li>Parse the obtained class definition into internal structures in the method area of the JVM </li></ul></ul></ul><ul><ul><ul><ul><li>The method area is a logical area of memory in the JVM that is used to store information about loaded classes/interfaces </li></ul></ul></ul></ul><ul><ul><ul><li>Create an instance of Class, which is associated with Foo </li></ul></ul></ul><ul><ul><li>These 3 activities are collectively called class loading. </li></ul></ul><ul><ul><li>After successful class loading, an instance of Foo is created and returned </li></ul></ul>
  7. 7. 5. Class Loaders in JVM <ul><li>ClassLoader </li></ul><ul><li>Every JVM has two types of class loaders </li></ul><ul><ul><li>Default class loaders </li></ul></ul><ul><ul><ul><li>Bootstrap class loader </li></ul></ul></ul><ul><ul><ul><ul><li>Used to find and load a set of standard class libraries (i.e. java.* classes) that are located in $JAVA_HOME$/jre/lib </li></ul></ul></ul></ul><ul><ul><ul><ul><li>-> e.g. $JAVA_HOME$/jre/lib/rt.jar </li></ul></ul></ul></ul><ul><ul><ul><li>Extension class loader </li></ul></ul></ul><ul><ul><ul><ul><li>Used to find and load a set of extension class libraries (i.e. javax.* classes) that are located in $JAVA_HOME$/jre/lib/ext </li></ul></ul></ul></ul><ul><ul><ul><li>System class loader (java.lang.Classloader) </li></ul></ul></ul><ul><ul><ul><ul><li>Used to find and load user-defined classes </li></ul></ul></ul></ul><ul><ul><li>Custom class loaders </li></ul></ul><ul><ul><ul><li>If a user wants to change the behavior of system class loader, the user can extend java.lang.Classloader as a Java class. The class is called a custom class loader </li></ul></ul></ul><ul><ul><ul><li>A custom class loader overloads the methods defined in java.lang.Classloader to implement its own class loading behavior. </li></ul></ul></ul><ul><ul><ul><ul><li>Different custom class loaders can specialize different class loading behaviors (policies) </li></ul></ul></ul></ul>
  8. 8. 6. Class Loaders Rules <ul><li>ClassLoader </li></ul><ul><li>Consistency Rule </li></ul><ul><ul><li>Class loaders never load the same class more than once </li></ul></ul><ul><li>Delegation Rule </li></ul><ul><ul><li>Class loaders always consult a parent class loader before loading a class </li></ul></ul><ul><li>Visibility Rule </li></ul><ul><ul><li>Classes can only “see” other classes loaded by their class loader’s delegation, the recursive set of a class’s loader and all its parent loaders </li></ul></ul>
  9. 9. 6. Visibility <ul><li>ClassLoader </li></ul>
  10. 10. 6. Visibility 실습 <ul><li>ClassLoader </li></ul><ul><li>Java Statics </li></ul>public class Dummy { public static int staticCount = 0; public Dummy(){ staticCount++; System.out.println(&quot;Instance #&quot; + staticCount + &quot; constructed.&quot;); } } public class StaticTest { public static void main(String[] args) { new Dummy(); new Dummy(); new Dummy(); new Dummy(); new Dummy(); } } Instance #1 constructed. Instance #2 constructed. Instance #3 constructed. Instance #4 constructed. Instance #5 constructed.
  11. 11. 6. Visibility 실습 <ul><li>ClassLoader </li></ul><ul><li>Java Statics </li></ul>public class Dummy { public static int staticCount = 0; public Dummy(){ staticCount++; System.out.println(&quot;Instance #&quot; + staticCount + &quot; constructed.&quot;); } } public class StaticTestClassLoader { public static void main(String[] args) throws Exception { URL[] url = {new File(&quot;../target/bin&quot;).toURL()}; URLClassLoader cl1 = new URLClassLoader(url); URLClassLoader cl2 = new URLClassLoader(url); URLClassLoader cl3 = new URLClassLoader(url); cl1.loadClass(&quot;Dummy&quot;).newInstance(); cl2.loadClass(&quot;Dummy&quot;).newInstance(); cl3.loadClass(&quot;Dummy&quot;).newInstance(); } } Instance #1 constructed. Instance #1 constructed. Instance #1 constructed.
  12. 12. 7. Delegation Model <ul><li>ClassLoader </li></ul>class NetworkClassLoader extends ClassLoader { String host; int port; public Class findClass(String name) { byte[] b = loadClassData(name); return defineClass(name, b, 0, b.length); } private byte[] loadClassData(String name) { // load the class data from the connection &nbsp;.&nbsp;.&nbsp;. } }
  13. 13. 7. Delegation Model <ul><li>ClassLoader </li></ul>
  14. 14. 7. Delegation Model 실습 <ul><li>ClassLoader </li></ul><ul><li>Java 1.1 Style </li></ul>public class TestClassLoader extends ClassLoader { protected Hashtable m_classes = new Hashtable(); protected boolean m_cacle = false; protected byte[] loadClassBytes(String name) throws ClassNotFoundException{ byte[] result = null; try{ FileInputStream in = new FileInputStream(&quot;../Target/bin/&quot; + name.replace('.', '/') + &quot;.class&quot;); ByteArrayOutputStream data = new ByteArrayOutputStream(); int ch; while((ch = in.read()) != -1) data.write(ch); result = data.toByteArray(); } catch (Exception e){ throw new ClassNotFoundException(name); } return result; } protected synchronized Class loadClass (String name, boolean resolve) throws ClassNotFoundException{ System.out.println(&quot; 요청된 Class : &quot; + name); Class result = (Class)m_classes.get(name); try{ if(result==null) return super.findSystemClass(name); else return result; } catch(Exception e) {} System.out.println(&quot;TestClassLoader Loading Class : &quot; + name); byte bytes[] = loadClassBytes(name); result = defineClass(name, bytes, 0, bytes.length); if(result == null) throw new ClassNotFoundException(name); if(resolve) resolveClass(result); m_classes.put(name, result); return result; } }
  15. 15. 7. Delegation Model 실습 <ul><li>ClassLoader </li></ul><ul><li>Java 1.2 Style </li></ul>public class TestClassLoader extends ClassLoader { protected byte[] loadClassBytes(String name) throws ClassNotFoundException{ byte[] result = null; try{ FileInputStream in = new FileInputStream(&quot;../Target/bin/&quot; + name.replace('.', '/') + &quot;.class&quot;); ByteArrayOutputStream data = new ByteArrayOutputStream(); int ch; while((ch = in.read()) != -1) data.write(ch); result = data.toByteArray(); } catch (Exception e){ throw new ClassNotFoundException(name); } return result; } protected Class findClass(String name) throws ClassNotFoundException{ System.out.println(&quot; 요청된 Class : &quot; + name); System.out.println(&quot;TestClassLoader Loading Class : &quot; + name); byte bytes[] = loadClassBytes(name); return defineClass(name, bytes, 0, bytes.length); } }
  16. 16. //java.lanag.ClassLoader 일부 protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { try { if (parent != null) { c = parent.loadClass(name, false); } else { c = findBootstrapClass0(name); } } catch (ClassNotFoundException e) { // If still not found, then invoke findClass in order // to find the class. c = findClass(name); } } if (resolve) { resolveClass(c); } return c; } 7. Delegation Model 실습 <ul><li>ClassLoader </li></ul><ul><li>Java 1.2 Style </li></ul>
  17. 17. 8. Standard Class Loader <ul><li>ClassLoader </li></ul><ul><li>Standard ClassLoader </li></ul>
  18. 18. 8. Standard Class Loader <ul><li>ClassLoader </li></ul><ul><li>Java Options </li></ul>
  19. 20. public class ClassLoaderTree { public static void printClassLoaderTree(ClassLoader l) { if(l== null){ System.out.println(&quot;BootStrap ClassLoader&quot;); return; } ClassLoader p = l.getParent(); if ( p!= null) { printClassLoaderTree(p); } else { System.out.println(&quot;BootStrap ClassLoader&quot;); } String u = &quot;&quot;; if ( l instanceof URLClassLoader) { u = getURLs( ((URLClassLoader)l).getURLs()); } // end of if () System.out.println(&quot;t|n&quot;+l+&quot; &quot; +u); } 8. Standard Class Loader <ul><li>ClassLoader </li></ul><ul><li>ClassLoader Tree </li></ul>public static String getURLs(URL[] urls) { if ( urls == null) { return &quot;{}&quot;; } // end of if () StringBuffer b = new StringBuffer(&quot;{&quot;); for ( int i = 0;i<urls.length;i++) { b.append( urls[i] ).append(&quot;:&quot;); } // end of for () b.append(&quot;}&quot;); return b.toString(); } public static void main(String[] args) { ClassLoaderTree.printClassLoaderTree (ClassLoaderTree.class.getClassLoader()); } }
  20. 21. <ul><li>java -classpath ./bin ClassLoaderTree </li></ul><ul><li>java -Djava.ext.dirs=./bin ClassLoaderTree </li></ul><ul><li>java -Xbootclasspath:.bin;D:JDKSDK13jrelibrt.jar;... ClassLoaderTree </li></ul>8. Standard Class Loader <ul><li>ClassLoader </li></ul>
  21. 22. <ul><li>What is a class loader? </li></ul><ul><ul><li>mechanism for loading classes into the JVM </li></ul></ul><ul><ul><li>subclass of java.lang.ClassLoader </li></ul></ul><ul><li>Hierarchical structure </li></ul><ul><ul><li>Parent-child relationships </li></ul></ul><ul><li>Uses delegation </li></ul><ul><ul><li>Load requests delegated to parent </li></ul></ul>Summary <ul><li>ClassLoader </li></ul><ul><li>ClassLoader Basics </li></ul>ClassLoader-A Class-X ClassLoader-B ClassLoader-C Class-Y Class-Z Class-Z
  22. 23. <ul><li>Unidirectional visibility </li></ul><ul><ul><li>Parent-loaded classes cannot see child-loaded classes </li></ul></ul><ul><ul><li>Thread.getContextClassloader() </li></ul></ul><ul><li>Unique Namespaces </li></ul><ul><ul><li>Classes referenced as classloader.classname </li></ul></ul><ul><li>Variety of class file locations </li></ul><ul><ul><li>File system </li></ul></ul><ul><ul><li>Databases </li></ul></ul><ul><ul><li>Remote server locations </li></ul></ul>Database Remote Server File system ClassLoader-A Class-X ClassLoader-B ClassLoader-C Class-Y Class-Z Class-R Class-D Summary <ul><li>ClassLoader </li></ul><ul><li>ClassLoader Basics </li></ul>
  23. 24. <ul><li>Bootstrap ClassLoader </li></ul><ul><ul><li>aka Primordial ClassLoader </li></ul></ul><ul><ul><li>Created by the JVM </li></ul></ul><ul><ul><li>Loads the JDK classes included in the JVM </li></ul></ul><ul><ul><li>(including java.lang.ClassLoader ) </li></ul></ul>Bootstrap ClassLoader Extensions ClassLoader JVM Application Shared Lib System ClassLoader <ul><li>System ClassLoader </li></ul><ul><ul><li>loads classes specified in the classpath </li></ul></ul><ul><ul><li>Loads applications, shared libraries, jars, etc. </li></ul></ul><ul><li>Extensions ClassLoader </li></ul><ul><ul><li>Loads JRE classes </li></ul></ul>JAR Summary <ul><li>ClassLoader </li></ul><ul><li>ClassLoader Basics </li></ul>
  24. 25. <ul><li>Determine Initial ClassLoader </li></ul><ul><li>Delegate to Parent ClassLoader </li></ul><ul><li>Class Loaded? </li></ul><ul><li>No – Delegate to Parent </li></ul><ul><li>Lastly – If class is not loaded in parent hierarchy then the Initial loader will attempt to load the class itself. </li></ul>JVM Class Loader A MyClass Class Loader B Class Loader C System ClassLoader Bootstrap ClassLoader Extension ClassLoader Summary <ul><li>ClassLoader </li></ul><ul><li>Typical Loading Scenario </li></ul>
  25. 26. Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved | Confidential 목차 <ul><li>Class Loader </li></ul><ul><li>Custom Class Loader </li></ul><ul><li>Diagnosing </li></ul>
  26. 27. 1. Java 내부의 ClassLoader <ul><li>Custom ClassLoader </li></ul><ul><li>java.security.SecureClassLoader </li></ul><ul><ul><li>Java 2 Platform 보안부분 지원 </li></ul></ul><ul><li>Java.net.URLClassLoader </li></ul><ul><ul><li>Java 2 Runtime Library 내부에서 유일하게 실제 구현된 ClassLoader </li></ul></ul><ul><li>sun.applet.AppletClassLoader </li></ul><ul><li>java.rmi.server.RMIClassLoader </li></ul><ul><ul><li>RMI runtime system 에서 class 를 마샬링하고 로딩하는 기능을 하는 wrapper class </li></ul></ul><ul><ul><li>sun.rmi.server.LoaderHandler Class 에 대한 다리 역할 </li></ul></ul><ul><li>BootStrap ClassLoader </li></ul><ul><ul><li>Native Code 로 구현 </li></ul></ul><ul><ul><li>Sun.boot.class.path 프로퍼티 참조 </li></ul></ul><ul><li>sun.misc.Launcher$ExtClassLoader </li></ul><ul><ul><li>Java.ext.dirs 프로퍼티 참조 </li></ul></ul><ul><li>sun.misc.Launcher$AppClassLoader </li></ul>
  27. 28. public static void main(String[] args) throws Exception { URL[] urlArray = { //new java.io.File(&quot;subdir.jar&quot;).toURL() // For loading-from-subdir.jar, uncomment the // above line and comment out the below line new java.io.File(&quot;subdir/&quot;).toURL() // For loading-from-subdirectory-subdir, // comment out the first line and uncomment // out this one }; URLClassLoader ucl = new URLClassLoader(urlArray); Object obj = ucl.loadClass(&quot;Hello&quot;).newInstance(); // Hello should print &quot;Hello&quot; to the System.out stream } 1.URLClassLoader 사용 예 <ul><li>ClassLoader </li></ul><ul><li>FileURLClient </li></ul>
  28. 29. public static void main(String[] args) throws Exception { URL[] urlArray = { new URL(&quot;http&quot;, &quot;www.javageeks.com&quot;, &quot;/SSJ/examples/&quot;) }; URLClassLoader ucl = new URLClassLoader(urlArray); Object obj = ucl.loadClass(&quot;com.javageeks.util.Hello&quot;).newInstance(); // Hello should print &quot;Hello from JavaGeeks.com!&quot; to the // System.out stream } 1.URLClassLoader 사용 예 <ul><li>ClassLoader </li></ul><ul><li>HttpURLClient </li></ul>
  29. 30. public static void main(String[] args) throws Exception { URL[] urlArray = { new URL(&quot;ftp&quot;, &quot;reader:password@www.javageeks.com&quot;, &quot;/examples&quot;) }; URLClassLoader ucl = new URLClassLoader(urlArray); Object obj = ucl.loadClass(&quot;Hello&quot;).newInstance(); } 1.URLClassLoader 사용 예 <ul><li>ClassLoader </li></ul><ul><li>FTPURLClient </li></ul>
  30. 31. 2. Why write a ClassLoader ? <ul><li>Custom ClassLoader </li></ul><ul><li>The default ClassLoader only knows how to load class files from the local file system. </li></ul><ul><ul><li>대부분의 경우에 만족 </li></ul></ul><ul><li>일반적으로 Local File System, Network 으로 부터 File 을 Loading 하는 것 이외에 다음과 같은 용도로 사용됨 </li></ul><ul><ul><li>Automatically verify a digital signature before executing untrusted code </li></ul></ul><ul><ul><li>Transparently decrypt code with a user-defined password </li></ul></ul><ul><ul><li>Create dynamically built classes customized to the user’s specific needs </li></ul></ul>
  31. 32. 3. Class Loader 확장 <ul><li>Custom ClassLoader </li></ul><ul><li>findClass(…) </li></ul><ul><ul><li>Class 이름으로 부터 Byte Code 를 얻는데 사용 </li></ul></ul><ul><ul><li>defineClass(…) 를 호출하여 Class Object 로 변환함 </li></ul></ul><ul><li>findResource(…) </li></ul><ul><ul><li>주어진 임의의 이름에 대한 Byte Code 를 얻는데 사용 </li></ul></ul><ul><ul><li>getResource(..) 에서 호출함 </li></ul></ul><ul><li>findLibrary(…) </li></ul><ul><ul><li>ClassLoader 가 native library 를 포함한 Class 를 Load 할 때 호출 </li></ul></ul><ul><ul><li>Binary Data 가 아닌 절대 경로명 만 반환 </li></ul></ul>protected Class findClass(String name) throws ClassNotFoundException { throw new ClassNotFoundException(name); } protected URL findResource(String name) { return null; } protected String findLibrary(String libname) { return null; }
  32. 33. 4. Class Loader 실습 <ul><li>Custom ClassLoader </li></ul><ul><li>FileSystemClassLoader </li></ul><ul><ul><li>Local File System 에서 Class Byte Code 를 뽑아내는 ClassLoader 제작 </li></ul></ul><ul><ul><li>.jar/.zip 에 대한 부분은 고려하지 않음 </li></ul></ul><ul><ul><li>ClassLoader Class 를 extends 하여 구현 </li></ul></ul><ul><ul><li>findClass(String name) 부분 overriding 구현 </li></ul></ul>java -classpath ./bin -Dloader.dir=./bin/ FileSystemClassLoader
  33. 34. 4. Class Loader 실습 <ul><li>Custom ClassLoader </li></ul><ul><li>CompilingClassLoader </li></ul><ul><ul><li>When a class is requested, see if it exists on the disk, in the current directory, or in the appropriate subdirectory </li></ul></ul><ul><ul><li>If the class is not available, but the source is, call the java compiler to generate the class file </li></ul></ul><ul><ul><li>If the class file does exist, check to see if it is older than its source code. If it is older than the source, call the java compiler to generate the class file. </li></ul></ul><ul><ul><li>If the compile fails, or if for any reason the class file could not be generated from existing source, throw a ClassNotFoundException </li></ul></ul><ul><ul><li>If we still don’t have the class, maybe it’s in some other library, so call findSystemClass to see if that will work </li></ul></ul><ul><ul><li>If we still don’t have the class, throw a ClassNotFoundException </li></ul></ul><ul><ul><li>Otherwise, return the class </li></ul></ul>java -classpath ./bin CCLRun Foo aaa bbb
  34. 35. 4. Class Loader 실습 <ul><li>Custom ClassLoader </li></ul><ul><li>HotDeploy </li></ul>java -classpath ./bin athena.loader.PointClient
  35. 36. 4. Class Loader 실습 <ul><li>Custom ClassLoader </li></ul><ul><li>Context Class Loader </li></ul>java -classpath ./bin DynamicLoader Echo aaa aaa aaa java -Djava.ext.dirs=./jar -classpath ./bin DynamicLoader Echo aaa aaa aaa java -Djava.ext.dirs=./jar -classpath ./bin FixedDynamicLoader Echo aaa aaa aaa
  36. 37. Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved | Confidential 목차 <ul><li>Class Loader </li></ul><ul><li>Custom Class Loader </li></ul><ul><li>Diagnosing </li></ul>
  37. 38. 1. Class Not Found <ul><li>Diagnosing </li></ul><ul><li>ClassNotFoundException </li></ul><ul><ul><li>Used String representation </li></ul></ul><ul><ul><li>(e.g. ClassLoader.LoadClass(className)) </li></ul></ul><ul><ul><li>Typically, dependent Class is only visible to children </li></ul></ul><ul><li>NoClassDefFoundError </li></ul><ul><ul><li>Class existed at compile time </li></ul></ul><ul><ul><li>Typically, dependent Class is only visible to children </li></ul></ul><ul><li>NoClassDefFoundException </li></ul><ul><ul><li>An interesting phenomenon: this Exception is not in the JDK, </li></ul></ul><ul><ul><li>but it appears in dozens of topics in developer forums  </li></ul></ul>EJB JAR STRUTS.JAR WAR B AppBForm WAR A AppAForm
  38. 39. <ul><li>ClassCastException </li></ul><ul><ul><li>same Class was loaded by two different ClassLoaders </li></ul></ul><ul><li>ClassCircularityError </li></ul><ul><ul><li>A Class and one of its dependents are both dependent on a third Class; different ClassLoaders are used to load that third Class </li></ul></ul>2. Class Cast <ul><li>Diagnosing </li></ul>EJB JAR public void utilityMethod (Object o) { ((Apple)o).doSomething(); } WAR B Apple WAR A Apple Apple CLASSCASTEXCEPTION
  39. 40. <ul><li>Place diagnostic statements in the application code </li></ul><ul><li>Place diagnostic statements in a custom ClassLoader </li></ul><ul><li>Place diagnostic statements in the core Java ClassLoaders. The -Xbootclasspath option makes to possible to supersede core Classes in a development environment. </li></ul><ul><li>Use the –verbose option </li></ul>C:>java -Xbootclasspath:C:debug;j2sdk1.4.2_03jrelibrt.jar … [all other boot.class.path jars] app.java 3. Getting Diagnostic Info. <ul><li>Diagnosing </li></ul>
  40. 41. import java.io.File; import java.net.MalformedURLException; import java.net.URLClassLoader; import java.net.URL; import demo.Rabbit; /** * Instantiates and displays a Rabbit. */ public class TopHat { public static void main (String args[]) { try { // Create a ClassLoader that knows where to find demo. Rabbit URL rabbitURL = new File(&quot;rabbit.jar&quot;).toURL(); URL[] urls = new URL[]{rabbitURL}; URLClassLoader rabbitClassLoader = new URLClassLoader(urls,Thread.currentThread().getContextClassLoader()); // Set the ContextClassLoader for the current Thread so that it can find Rabbit.class Thread.currentThread().setContextClassLoader(rabbitClassLoader); // Make a Rabbit appear. System.out.println(new Rabbit()); } catch (MalformedURLException malformedURLException) { malformedURLException.printStackTrace(); } } } <ul><li>TopHat.java </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  41. 42. package demo; public class Rabbit { } Rabbit.java rabbit.jar C:> jar tf rabbit.jar demo/ demo.Rabbit.class C:> javac –classpath rabbit.jar TopHat.java C:> java –classpath ./bin TopHat Command Line Compilation <ul><li>Rabbit.java </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  42. 43. <ul><li>TopHat should instantiate and display a String </li></ul><ul><li>representation of a Rabbit, even though </li></ul><ul><li>rabbit.jar is not referenced on the application </li></ul><ul><li>classpath. </li></ul>Actual Behavior C:>java TopHat Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: demo/Rabbit at TopHat.main(TopHat.java:23) Desired Behavior <ul><li>Desired Behavior Vs. Actual Behavior </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  43. 44. // Create a ClassLoader that knows where to find demo. Rabbit URL rabbitURL = new File(&quot;rabbit.jar&quot;).toURL(); URL[] urls = new URL[]{rabbitURL}; URLClassLoader rabbitClassLoader = new URLClassLoader(urls,Thread.currentThread().getContextClassLoader()); System.out.println(&quot;---> ClassLoader for TopHat: &quot; + TopHat.class.getClassLoader()); System.out.println(&quot;---> Before setting a custom ContextClassLoader, ContextClassLoader is: “); System.out.println( Thread.currentThread().getContextClassLoader()); // Set the ContextClassLoader for the current Thread so that it can find // Rabbit Thread.currentThread().setContextClassLoader(rabbitClassLoader); System.out.println(&quot;---> After setting a custom ContextClassLoader ContextClassLoader is: &quot;); System.out.println( Thread.currentThread().getContextClassLoader()); // Make a Rabbit appear. System.out.println(new Rabbit()); <ul><li>TopHat.java with Diagnostic Statements </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  44. 45. C:>java TopHat ---> ClassLoader for TopHat: sun.misc.Launcher$AppClassLoader@e80a59 ---> Before setting a custom ContextClassLoader, ContextClassLoader is: sun.misc.Launcher$AppClassLoader@e80a59 ---> After setting a custom ContextClassLoader, ContextClassLoader is: [email_address] Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: demo/Rabbit at TopHat.main(TopHat.java:28) <ul><li>Output From Diagnostics in the Application </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  45. 46. protected Class findClass(final String name) throws ClassNotFoundException { try { return (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws ClassNotFoundException { String path = name.replace('.', '/').concat(&quot;.class&quot;); Resource res = ucp.getResource(path, false); if (res != null) { try { return defineClass(name, res); } catch (IOException e) { throw new ClassNotFoundException(name, e); } } else { System.out.println(“--  Looked in:”); URL[] urls = getURLs(); for (int i = 0;i<urls.length;i++) { System.out.println(urls[i]); } throw new ClassNotFoundException(name); } } }, acc); } catch (java.security.PrivilegedActionException pae) { throw (ClassNotFoundException) pae.getException(); } } <ul><li>Diagnostics in java.net.URLClassLoader </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  46. 47. protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class c = findLoadedClass(name); if (c == null) { try { if (name.equals(&quot;demo.Rabbit&quot;)) System.out.println(&quot;---> &quot; + this + &quot;is asking parent (&quot; + parent + &quot;) to try to load &quot; + name + &quot;.&quot;); if (parent != null) { c = parent.loadClass(name, false); } else { c = findBootstrapClass0(name); } } catch (ClassNotFoundException e) { // If still not found, then call findClass in order // to find the class. if (name.equals(&quot;demo.Rabbit&quot;)) System.out.println(&quot;---> &quot; + name + &quot; was not found by parent (&quot; + parent + &quot;), so &quot; + this + &quot; will try.&quot;); c = findClass(name); } } if (resolve) { resolveClass(c); } return c; } void addClass(Class c) { if (c.toString().equals(&quot;class demo.Rabbit&quot;)) System.out.println(&quot;---> &quot; + this + &quot;loaded &quot; + c); classes.addElement(c); } private synchronized Class loadClassInternal(String name)throws ClassNotFoundException { if (name.equals(&quot;demo.Rabbit&quot;)) { System.out.println(&quot;JVM is requesting that &quot; + this +&quot; load &quot;+ name); } return loadClass(name); } <ul><li>Diagnostics in java.lang.ClassLoader </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  47. 48. ---> JVM is requesting that sun.misc.Launcher$AppClassLoader@e80a59 load demo.Rabbit ---> sun.misc.Launcher$AppClassLoader@e80a59 is asking parent (sun.misc.Launcher$ ExtClassLoader@1ff5ea7) to try to load demo.Rabbit. ---> sun.misc.Launcher$ExtClassLoader@1ff5ea7 is asking parent (null) to try to load demo.Rabbit. ---> demo.Rabbit was not found by parent (null), so sun.misc.Launcher$ExtClassLoader@1ff5ea7 will try. --> Looked in: file:/C:/j2sdk1.4.2_03/jre/lib/ext/dnsns.jar file:/C:/j2sdk1.4.2_03/jre/lib/ext/ldapsec.jar file:/C:/j2sdk1.4.2_03/jre/lib/ext/localedata.jar file:/C:/j2sdk1.4.2_03/jre/lib/ext/sunjce_provider.jar ---> demo.Rabbit was not found by parent (sun.misc.Launcher$ExtClassLoader@1ff5ea7), so sun.misc.Launcher$AppClassLoader@e80a59 will try. --> Looked in: file:/C:/ Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: demo/Rabbit at TopHat.main(TopHat.java:28) <ul><li>Output from Diagnostics in the Core Java Classes </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>java -Xbootclasspath/p:D:ClassloaderUtilbin -classpath ./bin TopHat
  48. 49. <ul><li>Regardless of how the Context ClassLoader is set , the classloader that loaded the calling Class will always be used to load a requested Class when no ClassLoader is specified </li></ul><ul><ul><li>new ClassName() </li></ul></ul><ul><ul><li>Class.forName(“package.ClassName”) </li></ul></ul><ul><li>Context ClassLoaders are used by </li></ul><ul><ul><li>JNDI </li></ul></ul><ul><ul><li>JAXP </li></ul></ul><ul><li>Analysis </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  49. 50. ClassLoader loader = Thread.currentThread().getContextClassLoader(); loader.loadClass(“demo.Rabbit”).newInstance(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class.forName(“demo.Rabbit”,true, loader).newInstance(); – or – <ul><li>Possible Solutions </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  50. 51. ---> [email_address] is asking parent (sun.misc.Launcher$AppClassL oader@e80a59) to try to load demo.Rabbit. ---> sun.misc.Launcher$AppClassLoader@e80a59 is asking parent (sun.misc.Launcher$ ExtClassLoader@1ff5ea7) to try to load demo.Rabbit. ---> sun.misc.Launcher$ExtClassLoader@1ff5ea7 is asking parent (null) to try to load demo.Rabbit. ---> demo.Rabbit was not found by parent (null), so sun.misc.Launcher$ExtClassLo ader@1ff5ea7 will try. --> Looked in: file:/C:/j2sdk1.4.2_03/jre/lib/ext/dnsns.jar file:/C:/j2sdk1.4.2_03/jre/lib/ext/ldapsec.jar file:/C:/j2sdk1.4.2_03/jre/lib/ext/localedata.jar file:/C:/j2sdk1.4.2_03/jre/lib/ext/sunjce_provider.jar ---> demo.Rabbit was not found by parent (sun.misc.Launcher$ExtClassLoader@1ff5e a7), so sun.misc.Launcher$AppClassLoader@e80a59 will try. --> Looked in: file:/C:/ ---> demo.Rabbit was not found by parent (sun.misc.Launcher$AppClassLoader@e80a5 9), so java.net.URLClassLoader@defa1a will try. ---> [email_address] loaded class demo.Rabbit [email_address] <ul><li>Rabbit Appears </li></ul>3. 실습 <ul><li>Diagnosing </li></ul>
  51. 52. 감사합니다 . Copyright © 2004 Samsung SDS Co.,Ltd. All rights reserved | Confidential 대표전화 : +82-2-6484-0930 E-mail: chris_lee@samsung.com http://www.sds.samsung.co.kr

×