More recent exposure to SOLR, and feeling that SOLR provides a cool plug-in development approach, SOLR provides developers with a core API jar package, and developers who want to extend a certain feature of SOLR, such as Chinese participle, simply inherit the word interface provided by SOLR to add their own implementations, It then copies its own word jar package to the SOLR specified directory and configures it in the SOLR configuration file, and the reboot takes effect.
This article will involve custom class loading, so first introduce the Java class Loader principle and working mechanism, the familiar students can skip directly.
Java class loader
A class loader is a class that is used to load class files. Java source code is compiled into class files through the Javac compiler. The JVM then executes the byte code in the class file to execute the program. The class loader is responsible for loading class files for file systems, networks, or other sources. There are three class loaders that are used by default: The Bootstrap class loader, the extension class loader, and the System class loader (or called the application ClassLoader). The classes that each type of loader is responsible for loading are also different.
JVM three predefined type class loaders
Bootstrap ClassLoader: Will be stored in the <java_home>\lib directory, or in the path specified by the-xbootclasspath parameter, and is recognized by the virtual machine (only by file name, such as Rt.jar Class libraries whose names do not conform are loaded into virtual machine memory even if they are not loaded in the Lib directory. The boot class loader cannot be referenced directly by a JAVA program Extension ClassLoader: Loads all the class libraries in the <java_home>\lib\ext directory, or in the path specified by the Java.ext.dirs system variable. Developers can use the extended class loader directly. Application ClassLoader: is responsible for loading the class library specified on the user classpath (ClassPath), which can be used directly by the developer.proxy mode for class loaderWhen the class loader tries to find its own byte code for a class and defines it, it first proxies its parent class loader, and the parent loader tries to load the class first, and so on. Before introducing the motives behind the agent model, it is first necessary to explain how the Java virtual machines determine that two Java classes are the same. The Java virtual machine depends not only on whether the full name of the class is the same, but also on whether the class loader that loads the class is the same. The two classes are considered to be identical only if they are the same. Even the same byte code is different when the class is loaded by a different classloader. such as a Java class Com.example.Sample, compiled after the production of bytecode file Sample.class. Two different ClassLoader Classloadera and Classloaderb read the Sample.class file separately and define two instances of the Java.lang.Class class to represent this class. These two instances are not the same. For Java virtual machines, they are different classes. An attempt to assign values to objects of these two classes throws a Run-time exception classcastexception.
The bottom line is that when you look up a class, you start from down to the top, and you load a class up and down.
Custom class Loader
Because we need to load the jar file under the specified path, we need a custom class loader to scan the jar package under the specified path, as follows:
Package Com.bytebeats.switcher.core;
Import Com.bytebeats.switcher.util.IoUtils;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Java.io.File;
Import Java.io.FileFilter;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import Java.net.URLClassLoader; /** * * @author Ricky Fung * @create 2016-11-12 14:27/public class Pluginclassloader {private final Logger Logge
R = Loggerfactory.getlogger (Pluginclassloader.class);
Private URLClassLoader ClassLoader;
Public Pluginclassloader (String jarfiledir) {This (new File (JARFILEDIR), null);
Public Pluginclassloader (File jarfiledir) {This (jarfiledir, null); Public Pluginclassloader (File Jarfiledir, ClassLoader parent) {This.classloader = Createclassloader (Jarfiledir, Pare
NT); } public void Addtoclassloader (final String baseDir, Final filefilter filter, Boolean quiet) {File base = new F
Ile (BaseDir); if (base!= null && base.exists () && base.isdirectory ()) {File[] Files = base.listfiles (filter);
if (Files = null | | files.length = 0) {if (!quiet) {logger.error ("No files added to ClassLoader from Lib:" + BaseDir + "(Resolved as:" + base.getabsolutepath () + ").");}
else {This.classloader = Replaceclassloader (ClassLoader, base, filter);
} else {if (!quiet) {logger.error ("Can" t find (or read) directory to add to ClassLoader: "+ baseDir
+ "(Resolved as:" + base.getabsolutepath () + ").");}}}
Private URLClassLoader Replaceclassloader (final URLClassLoader oldloader, final File base, Final FileFilter filter) {
if (null!= base && base.canread () && base.isdirectory ()) {file[] files = base.listfiles (filter); if (null = Files | | | 0 = files.length) {logger.error ("Replaceclassloader base dir:{} is empty", Base.getabsolutepa
th ());
return oldloader; } logger.error ("Replaceclassloader base dir: {}, Size: {}", BasE.getabsolutepath (), files.length);
url[] oldelements = Oldloader.geturls ();
url[] elements = new Url[oldelements.length + files.length];
System.arraycopy (oldelements, 0, elements, 0, oldelements.length);
for (int j = 0; J < Files.length; J +) {try {URL element = Files[j].touri (). Normalize (). Tourl ();
Elements[oldelements.length + j] = element;
Logger.info ("Adding ' {} ' to ClassLoader", element.tostring ());
catch (Malformedurlexception e) {logger.error ("Load Jar file Error", E);
} ClassLoader oldparent = Oldloader.getparent (); ioutils.closequietly (Oldloader);
Best effort return urlclassloader.newinstance (elements, oldparent);
return oldloader; Private URLClassLoader Createclassloader (final File Libdir, ClassLoader parent) {if (null = = parent) {Parent
= Thread.CurrentThread (). Getcontextclassloader (); Return Replaceclassloader (urlclassloader.newinstance (new url[0), ParenT), libdir, NULL); Class<?> loadclass (String className) throws classnotfoundexception{return Classloader.loadclass (clas
sname);
}
}
For ease of use, the PlugInManager is provided
Package Com.bytebeats.switcher.core;
Import Com.bytebeats.switcher.util.StringUtils;
Import Java.io.File; /** * ${description} * * @author Ricky Fung * @create 2016-11-12 14:35 * * public class PlugInManager {private VO
Latile static PlugInManager Mgr;
Private Pluginclassloader Pluginclassloader;
Private volatile Boolean init; Private PlugInManager () {} public static PlugInManager Getmgr () {if (mgr==null) {synchronized (Pluginmanager.class)
{if (mgr==null) {mgr = new PlugInManager ();
}} return Mgr;
} public <T> T getplugin (String className, class<t> required) {class<?> CLS = null;
try {cls = Pluginclassloader.loadclass (className);
catch (ClassNotFoundException e) {throw new IllegalArgumentException ("Can not find class:" +classname, E); } if (required.isassignableFrom (CLS) {try {return (T) cls.newinstance ();
catch (Exception e) {throw new IllegalArgumentException ("Can Not newinstance class:" +classname, E);
} throw new IllegalArgumentException ("Class:" +classname+ "not sub class of" +required); public void Addexternaljar (String basepath) {if (Stringutils.isempty (BasePath)) {throw new Ill
Egalargumentexception ("BasePath can not be empty!");
File dir = new file (basepath);
if (!dir.exists ()) {throw new IllegalArgumentException ("BasePath NOT EXISTS:" +basepath); } if (!dir.isdirectory ()) {throw new IllegalArgumentException ("BasePath must be a directory:" +basepath)
;
} if (!init) {init= true;
Pluginclassloader = Doinit (BasePath);
}else{Pluginclassloader.addtoclassloader (BasePath, NULL, TRUE);
}
} Private synchronized Pluginclassloader doinit (String basepath) {Pluginclassloader Pluginclassloader = new Plug
Inclassloader (BasePath);
return pluginclassloader;
}
}
examples of plug-in development
The following is a simple example to demonstrate how to implement plug-in development
EXAMPLE-API Storage Core API interface, Example-plugin is the plug-in project to provide EXAMPLE-API API interface implementation, Example-host is the main program it will be in the boot to load plugin.
The API interfaces in Example-api are as follows:
Package Com.bytebeats.switcher.example.api;
/**
* ${description}
* *
@author Ricky Fung
* @create 2016-11-12
15:30/public interface ihelloservice {
string Hello (string msg);
}
Package Com.bytebeats.switcher.example.api;
Import Com.bytebeats.switcher.example.domain.User;
Import java.util.List;
/**
* ${description}
* *
@author Ricky Fung
* @create 2016-11-12
16:09/public interface Iuserservice {
list<user> getusers ();
int update (user user);
}
The API interface in Example-plugin is implemented as follows:
Package com.bytebeats.example.plugin;
Import Com.bytebeats.switcher.example.api.IHelloService;
/**
* ${description}
* *
@author Ricky Fung
* @create 2016-11-12
16:13/public class Helloserviceimpl implements Ihelloservice {
@Override public
string Hello (String msg) {
System.out.println ("Hello [" + msg + "]");
return "Hello [" + msg + "]";
}
Package com.bytebeats.example.plugin;
Import Com.bytebeats.switcher.example.api.IUserService;
Import Com.bytebeats.switcher.example.domain.User;
Import java.util.ArrayList;
Import java.util.List;
/**
* ${description}
* *
@author Ricky Fung
* @create 2016-11-12
16:14/public class Userserviceimpl implements Iuserservice {
@Override public
list<user> getusers () {
List<user > list = new arraylist<> ();
List.add (New User ("Ricky", "12345"));
List.add (New User ("Kobe", "AAA"));
List.add (New User ("Jordan", "Root"));
return list;
}
@Override Public
int update (user user) {
System.out.println ("Update user = [+ user +]");
User.setpassword ("Hello");
return 1;
}
}
The startup classes in Example-host are as follows:
Package com.bytebeats.example.host;
Import Com.bytebeats.switcher.core.PluginManager;
Import Com.bytebeats.switcher.example.api.IHelloService;
Import Com.bytebeats.switcher.example.api.IUserService;
Import Com.bytebeats.switcher.example.domain.User;
Import java.util.List;
/**
* Hello world!
* */Public
class App. {public
static void Main (string[] args) {
PlugInManager PlugInManager = pluginm Anager.getmgr ();
Pluginmanager.addexternaljar ("D:\\osgi");
Ihelloservice HelloService = Pluginmanager.getplugin ("Com.bytebeats.example.plugin.HelloServiceImpl", Ihelloservice.class);
Helloservice.hello ("Ricky");
Iuserservice UserService = Pluginmanager.getplugin ("Com.bytebeats.example.plugin.UserServiceImpl", Iuserservice.class);
list<user> list = Userservice.getusers ();
SYSTEM.OUT.PRINTLN ("list = [" + list + "]");
Userservice.update (New User ("Test", "Test"));
}
Note: Before running, you need to example-plugin the project into a jar package, and then copy it to any path, this is the D:\osgi directory.
code Download All code has been uploaded to Github:https://github.com/tifg/cherry