Dynamically load jars for custom business

Source: Internet
Author: User

In the actual business, we often encounter the need to implement different business logic according to different users, if according to the most simple and rude practice, of course, is to use if else ... To achieve.

But as a social person, how can this show our combat effectiveness, below we come to implement a method of cattle fork.

Specific ideas:

The different business logic is put into different jar packages according to the user, then the system can realize the respective business by reading the jar package;

In the future, even if the user's logic changes, as long as the jar package upload to the server, it can be implemented dynamically, does not affect the production environment.

1. Interface

 Public Interface interfaceaction {    public  String getId ();      Public Abstract String Action ();}

2. New Project

Action.ext.bj

Pom.xml relies on the base package

<Dependency>            <groupId>Com.qn</groupId>            <Artifactid>Action.base</Artifactid>            <version>0.0.1-snapshot</version>
</Dependency>

Implementing interfaces

 Public classExtbjImplementsinterfaceaction {/**      * @seeAction.base.code.interfaceaction#getid ()*/@Override PublicString getId () {return"BJ"; }    /**      * @seeaction.base.code.interfaceaction#action ()*/@Override PublicString Action () {return"This is BJ ...."; }}

Follow this project to create a new Action.ext.nt

After implementing the interface, export the jar package and store it in a directory;

3. Complete the custom Myclassloader

 Public classMyclassloader {PrivateClassLoader Loader; Privatemap<string, interfaceaction> ActionMap =NewHashmap<>(); /*** Getter method for property <tt>actionmap</tt>. *      * @returnProperty value of ActionMap*/     PublicMap<string, interfaceaction>Getactionmap () {returnActionMap; }    /*** Setter method for property <tt>actionmap</tt>. *      * @paramActionMap value to being assigned to property ActionMap*/     Public voidSetactionmap (map<string, interfaceaction>ActionMap) {         This. ActionMap =ActionMap; }     Public voidload (String jarfilename) {jarfile jarfile=NULL; Try{File File=NewFile (jarfilename); URL URL=NewURL ("File:" +jarfilename); Loader=NewURLClassLoader (Newurl[] {URL});            File.lastmodified (); Jarfile=Newjarfile (file); Enumeration<JarEntry> EnumFiles =jarfile.entries ();            Jarentry entry; //traverse each file in a jar package             while(Enumfiles.hasmoreelements ()) {entry=enumfiles.nextelement (); String Classfullname=Entry.getname (); //process only. class Files                if(Classfullname.indexof ("Meta-inf") < 0 && Classfullname.indexof (". Class") > 0) {String className= classfullname.substring (0, Classfullname.length ()-6). ReplaceAll ("/", "."); //to load a class in a jar package using the current class loaderSYSTEM.OUT.PRINTLN ("Load class start:" +className); Class<?> Clazz =Loader.loadclass (className); System.out.println ("Load class End:" +clazz); BooleanFlag = Isinterface (Clazz, interfaceaction.class); if(flag) {Interfaceaction ia= ((class<interfaceaction>). Clazz). newinstance ();                        Actionmap.put (Ia.getid (), IA);                    System.out.println (ACTIONMAP); }                }            }        } Catch(Exception e) {e.printstacktrace (); }    }    /*** Whether the interface is implemented *@paramc *@paramSzinterface *@return     */    Private BooleanIsinterface (class C, class Szinterface) {class[] face=c.getinterfaces ();  for(inti = 0, j = face.length; I < J; i++) {            if(Face[i].equals (szinterface)) {return true; }        }        return false; }}

4. Next up is test.

 Public Static void Main (string[] args) {        new  myclassloader ();        Ml.load ("D:\\temp\\action.ext.bj.jar");        Ml.load ("D:\\temp\\action.ext.nt.jar");         = Ml.getactionmap (). Get ("NT"). Action ();        System.out.println (s);    }
Load class Start:action.ext.bj.ExtBj Load class end: class action.ext.bj.ExtBj {[email protected]} Load class Start:action.ext.nt.ExtNt Load class end: class action.ext.nt.ExtNt {[email protected], [email protected]}   is nt .....

Sir Alex said: "It's done ...

Dynamically load jars for custom business

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.