Java Class Loader Code Example

Java Class Loader Code Example

Sometimes, client only has interface, need to download class implementation from server. In this case, we need to write our own class loader.

There are 2 ways:

1. In client side, if our class loader has not loaded this class, open a socket to server and read class binary from server. This requires server has server socket to listen connection, and return class binary.


package org.codeexample.classloader.client;

public class NetworkClassLoader extends ClassLoader {

private String host;

private int port;

public NetworkClassLoader(String host, int port) {

super();

this.host = host;

this.port = port;

}

public Class findClass(String className) {

Class result = this.findLoadedClass(className);

if (result != null) {

return result;

}

byte[] b = loadClassData(className);

return defineClass(className, b, 0, b.length);

}

private byte[] loadClassData(String name) {

// create a connection and load the class binary from remote machine

return null;

}

public String getHost() {

return host;

}

public int getPort() {

return port;

}

public static void main(String[] args) throws Exception {

ClassLoader classLoader = new NetworkClassLoader("host", 8080);

Class clazz = Class.forName("invalid", false, classLoader);

Object o = clazz.newInstance();

System.err.println(o);

}

}

2. Another way is that, after server accepts a connection, as a last step, server would return a map which stores binary of all classes client needed.

2.Client would save the map and our class loader would use the map to load remote class binary.

package org.codeexample.classloader.client;

public class NetworkClassLoader2 extends ClassLoader {

private Map codeBytes = new HashMap();

protected Class findClass(String className) throws ClassNotFoundException {

Class result = this.findLoadedClass(className);

if (result != null) {

return result;

}

if (codeBytes.containsKey(className)) {

byte[] code = (byte[]) codeBytes.get(className);

return defineClass(className, code, 0, code.length);

} else {

throw new ClassNotFoundException("Unable to find class "

+ className);

}

}

public Map getCodeBytes() {

return codeBytes;

}

/**

* At the last step, server return code binary, client would call this and

* save this binary

*

* @param codeBytes

*/

public void setCodeBytes(Map codeBytes) {

this.codeBytes = codeBytes;

}

public static void main(String[] args) throws Exception {

ClassLoader classLoader = new NetworkClassLoader2();

// Class clazz = classLoader.loadClass("invalid"); //

// NetworkClassLoader2.class.getName()

// Object o = clazz.newInstance();

// System.err.println(o);

Class clazz = Class.forName("invalid", false, classLoader);

Object o = clazz.newInstance();

System.err.println(o);

}

}

The following is the code that server uses to read class binary.

package org.codeexample.classloader.server;

public class CodeSourceHolder {

private static HashSet classes = new HashSet();

public static void addClass(Class clazz) {

classes.add(clazz);

}

public static void main(String[] args) {

addClass(CodeSourceHolder.class);

Map map = getCodeBytes();

Iterator it = map.keySet().iterator();

while (it.hasNext()) {

String clazz = (String) it.next();

byte[] classBytes = (byte[]) map.get(clazz);

System.out.println(clazz + ", class bytes[" + classBytes.length

+ "]");

}

}

public static Map getCodeBytes() {

Map map = new HashMap();

Iterator it = classes.iterator();

while (it.hasNext()) {

try {

Class type = (Class) it.next();

map.put(type.getName(), getCodeBytes(type));

} catch (IOException e) {

e.printStackTrace();

}

}

return map;

}

private static byte[] getCodeBytes(Class clazz) throws IOException {

String name = clazz.getName();

int lastPoint = name.lastIndexOf('.');

if (lastPoint != -1)

name = name.substring(lastPoint + 1);

String resource = name + ".class";

InputStream is = null;

try {

is = clazz.getResourceAsStream(resource);

byte[] codeSource = new byte[is.available()];

is.read(codeSource, 0, codeSource.length);

return codeSource;

} finally {

if (is != null) {

is.close();

}

}

}

}

The following is sample code to demonstrate how to use class loader.

package org.codeexample.classloader;

public class ClassLoaderExample {

public static void testURLClassLoader(String className) throws Exception {

URLClassLoader loader = new URLClassLoader(new URL[] { new URL(

"http://www.codeexample.com/classes/") });

Class c = loader.loadClass(className);

Object o = c.newInstance();

}

public static void testLoadLocalClass(String className) throws Exception {

URLClassLoader loader = new URLClassLoader(new URL[] { new URL(

"file://D:/ws/my-java/bin/") });

Class c = loader.loadClass(className);

Object o = c.newInstance();

// InterfaceA a = (InterfaceA) o;

// System.err.println(a.helloWorld());

}

public static void testContextLocalClass(String className) throws Exception {

String url = "some URL";

ClassLoader previous = Thread.currentThread().getContextClassLoader();

// Create a class loader using the URL as the codebase

// Use previous as parent class loader to maintain current visibility

ClassLoader current = URLClassLoader.newInstance(new URL[] { new URL(

url) }, previous);

Thread.currentThread().setContextClassLoader(current);

}

}

Post a Comment

Labels

Java (159) Lucene-Solr (110) Interview (61) All (58) J2SE (53) Algorithm (45) Soft Skills (36) Eclipse (34) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Troubleshooting (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Http Client (8) Maven (8) Problem Solving (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) Dynamic Languages (5) IDE (5) Lesson Learned (5) Programmer Skills (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) System Design (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts