Custom ClassLoader Load Class---Eclipse plugin development

Source: Internet
Author: User

There are many of our code that dynamically load classes, but there are some problems with using Eclipse development plugin.
For example, a type of class is required to be used in plugin, but because plugin's running environment is inconsistent with the run-time environment, you encounter classnotfoundexception problems in plugin development. In this case, you will customize the ClassLoader and then use it in plugin. At the same time, a problem to be noted is: in the dynamic home in the class, it is best not to use Xxx.getclass (). getClassLoader () or Xxx.class.getClassLoader (), Because this can lead to classnotfountexception, it is best to use Thread.CurrentThread (). Getcontextclassloader ().
This way, when you use custom ClassLoader, you don't have to modify the code to put the custom ClassLoader in the thread's contextclassload.
Code for Classloade:

/*
* Created on 2005-12-1
*/
Package org.jsports.plugin.classLoader;

Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.Channels;
Import Java.nio.channels.FileChannel;
Import Java.nio.channels.WritableByteChannel;
Import java.util.ArrayList;
Import java.util.List;


/**
* @author Kobye
*/
public class Jsportsclassloader extends ClassLoader {
Private String dir;

Public Jsportsclassloader (ClassLoader parent,string dir) {
Super (parent);
This.dir = dir;
}


Protected Class Findclass (String name) throws ClassNotFoundException {
byte[] bytes = loadclassbytes (name);
Class Theclass = defineclass (name, bytes, 0, bytes.length);
if (Theclass = = null) {
throw new Classformaterror ();
}
return theclass;
}


Private byte[] Loadclassbytes (String className) throws ClassNotFoundException {
try {
String classfile = Getclassfile (className);
FileInputStream fis = new FileInputStream (classfile);
FileChannel Filec = Fis.getchannel ();
Bytearrayoutputstream BAOs = new
Bytearrayoutputstream ();
Writablebytechannel OUTC = Channels.newchannel (BAOs);
Bytebuffer buffer = bytebuffer.allocate (1024);
while (true) {
int i = filec.read (buffer);
if (i = = 0 | | | = = = 1) {
Break
}
Buffer.flip ();
Outc.write (buffer);
Buffer.clear ();
}
Fis.close ();
return Baos.tobytearray ();
catch (IOException Fnfe) {
throw new ClassNotFoundException (ClassName);
}
}


private string Getclassfile (string name) {
StringBuffer sb = new StringBuffer (dir);
Name = Name.replace ('. ', File.separatorchar) + ". Class";
Sb.append (file.separator + name);
return sb.tostring ();
}


Protected URL FindResource (String name) {
try {
URL url = super.findresource (name);
if (URL!= null) {
return URL;
}
url = new URL ("file:///"+ convername (name));
return URL;
catch (Malformedurlexception Mue) {
return null;
}
}


private string Convername (string name) {
StringBuffer sb = new StringBuffer (dir);
Name = Name.replace ('. ', File.separatorchar);
Sb.append (file.separator + name);
return sb.tostring ();
}

private string GetClassName (String Dir,file f) {
String name = F.getabsolutepath ();
if (Name.startswith (dir)) {
Name = Name.substring (Dir.length (), name.length ());
}
Name = Name.replace (File.separatorchar, '. ');
if (Name.endswith (". Class")) {
Name = Name.substring (0,name.length ()-". Class". Length ());
}
return name;
}
Private List Getallfiles (File base) {
File[]dirs = Base.listfiles (New Classfilefilter ());
File[]classfile = Base.listfiles (New Classfilenamefilter ());
List files = new ArrayList ();
for (int i=0;i<classfile.length;i++) {
Files.add (Classfile[i]);
}
for (int i=0;i<dirs.length;i++) {
Files.addall (Getallfiles (dirs[i));
}
return files;
}

Private file Getdirbyname (file dir,string dirname,string baseDir) {
if (!dir.isdirectory ()) {
return null;
}
String Dirpath = Dir.getabsolutepath ();
if (Dirpath.startswith (BaseDir)) {
Check the file dir
Dirpath = dirpath.substring (Basedir.length (), dirpath.length ());
System.out.println ();
if (Dirpath.endswith ("model")) {
return dir;
}
}
File[]files = Dir.listfiles ();
for (int i=0;i<files.length;i++) {
File f = getdirbyname (Files[i],dirname,basedir);
if (f!=null) {
return F;
}
}
return null;
}

}


The function of this classloader is to load all classes in the Model directory under the DIR path.
And then call this:
String path = This.getcurrentproject (). GetLocation (). ToFile (). GetAbsolutePath () + "
//bin";
Thread.CurrentThread (). Setcontextclassloader (New Jsportsclassloader (Thread.CurrentThread). Getcontextclassloader (), path));

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.