Java Class Conflict Location ideas

Source: Internet
Author: User

Java's parent-class delegate loading mechanism, brings great convenience and efficiency while also brings a lot of trouble, the most direct is the problem caused by class conflict, the following scenarios do not know if you are a little familiar.   The class conflicts defined in this article are defined as classes that are under the same namespace are scattered in the jar package that does not pass through. 1, caused by the injection system confusion. 2, resulting in type judgment system confusion, such as if ((Paramobject instanceof Classs) judgment failure 3, different versions of the class implementation method has upgraded such as Ajar package support GETXX (A, B), while the other Jar is only Getxx (A) 4, In the mysterious disappearance of data in the operation, such as method a jar has method void A (b b), the method of calling a in C package the incoming object B and B in ajar are loaded with class conflict B.  The result of the operation is to be known.  One of the problems with this phenomenon is that the programmer goes back to saying that my code is fine, and that my local is normal ...., and so on, try to solve these problems. 1, the individual think first to the class loading mechanism to have a proper understanding. Take the current popular Tomcat as an example: load order what the person thinks is more detailed review. HTTP://WWW.CNBLOGS.COM/XING901022/P/4574961.HTMLHTTP://WWW.IBM.COM/DEVELOPERWORKS/CN/JAVA/J-LO-CLASSLOADER/2, Locate my Classpath or the project will load from those paths and find out which one of my programs is loading? You can use this method to find out which classes in a file are likely to cause conflicts.
Importjava.io.IOException;ImportJava.net.URL;ImportJava.net.URLDecoder;Importjava.util.Enumeration;ImportJava.util.jar.JarEntry;ImportJava.util.jar.JarFile;ImportJava.io.*;  Public classJarfinder { Public Static voidFindclassinjar (String jarname)throwsIOException {String FilePath=Jarname;if(Filepath.endswith (". Jar")) {} Elsereturn; java.util.jar.JarFile file=NewJarfile (FilePath); Enumeration<JarEntry> Entrys =file.entries (); while(Entrys.hasmoreelements ()) {Jarentry jar=entrys.nextelement (); String Tmpjarname=jar.getname (); Tmpjarname= Tmpjarname.replace ('/', '. '));if(Tmpjarname.contains ("Javax.mail.Multipart") {System.out.println (tmpjarname+ " " +file.getname ());}} File.close ();} Final Static voidShowallfileindir (File dir)throwsException {file[] fs=dir.listfiles (); for(inti = 0; i < fs.length; i++) {String file=Fs[i].getabsolutepath (); Findclassinjar (file);if(Fs[i].isdirectory ()) {Try{showallfileindir (fs[i]);}Catch(Exception e) {}}}}  Public Static voidMain (string[] args)throwsException {File root=NewFile ("C:/Program Files/java/jdk1.8.0_102/jre/lib/ext"); Showallfileindir (root);}}

3, reduce the number of related JAR Package 1, class unity, such as the different projects deployed on Tomcat each project has jar A, then you might want to put jar A in the Tomcat/common/lib directory. 2. Remove the jar from the project as much as possible. This method can usually solve a large part of the problem, the individual think is also a key way to solve such problems. 4, the code version of the unified solution to the problem is the best way to prevent. The underlying jar packages that are deployed under the same tomcat should be as uniform as possible to address this issue from the institutional and normative. It's best to have a company-dependent repository, MAVEN is a good way to manage, and the company processes dependencies at a consistent pace. 5. For the order that cannot be removed can be loaded by the control Jar Package 6, confirm that the unwanted jar package has been removed from the relevant path.  Personally, the jar was removed from the project's dependencies, but the jar still exists under the Lib path, which is still being beaten into the bag and depressed for two days. Other methods that may be used to locate the class path are:
 Public StaticString GetProjectPath () {Java.net.URL URL= Oracle.sql.NCLOB.class. Getprotectiondomain (). Getcodesource (). GetLocation (); String FilePath=NULL;Try{FilePath= Java.net.URLDecoder.decode (Url.getpath (), "Utf-8");} Catch(Exception e) {e.printstacktrace ();}if(Filepath.endswith (". Jar")) FilePath= filepath.substring (0, Filepath.lastindexof ("/") + 1); Java.io.File File=NewJava.io.File (FilePath); FilePath=File.getpath ();returnFilePath;}  Public Staticstring Getrealpath () {string Realpath= Oracle.sql.NCLOB.class. getClassLoader (). GetResource (""). GetFile ();//java.io.File File = new Java.io.File (realpath);//Realpath = file. ();System.out.println (realpath);Try{Realpath= Java.net.URLDecoder.decode (Realpath, "Utf-8");} Catch(Exception e) {e.printstacktrace ();}returnRealpath;}  Public StaticString Getapppath (class<?>CLS) {//checks whether the parameter passed in by the user is emptyif(CLS = =NULL)Throw NewJava.lang.IllegalArgumentException ("parameter cannot be empty!") "); ClassLoader Loader=Cls.getclassloader ();//get the full name of the class, including the package nameString Clsname =cls.getname ();//The simple decision here is whether it is a Java base Class library that prevents users from passing in the JDK's built-in class libraryif(Clsname.startswith ("java.") | | clsname.startswith ("javax.")) {Throw NewJava.lang.IllegalArgumentException ("Do not transfer the system class! ");}//change the class file's full name to the path formString Clspath = Clsname.replace (".", "/") + ". Class"; System.out.println (Clspath); //Call ClassLoader's GetResource method, passing in the class file name that contains the path informationJava.net.URL URL =Loader.getresource (clspath);//getting path information from a URL objectString Realpath =Url.getpath (); System.out.println (Realpath);//Remove the protocol name "file:" From the path informationintpos = Realpath.indexof ("File:");if(Pos >-1) {Realpath= realpath.substring (pos + 5);}//System.out.println (realpath);//get the path where the class is located by removing the part of the path information that contains the class file information last//pos = Realpath.indexof (Clspath);//Realpath = realpath.substring (0, pos-1);//if the class file is packaged in a file such as a jar, remove the package file name of the corresponding jar, etc.//if (Realpath.endswith ("!")) {//Realpath = realpath.substring (0, Realpath.lastindexof ("/"));//}//java.io.File File = new Java.io.File (realpath);//Realpath = File.getabsolutepath (); Try{Realpath= Java.net.URLDecoder.decode (Realpath, "Utf-8");} Catch(Exception e) {Throw NewRuntimeException (e);}returnRealpath;}

Judging from the two sides of the problem. This kind of loading mechanism can also bring me convenience side. For example, if we want to modify the implementation of Class B in jar A, and we do not have the source code, then this loading mechanism is very useful. We only need to build in the project SRC in accordance with the package name of B. However, when using this method, you should pay attention to the scope of the class impact, try not to do this on the common class, otherwise it will cause some uncontrolled risk.

Java Class Conflict Location ideas

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.