The influence of Java different classloader on instanceof keyword operation

Source: Internet
Author: User

Content: For any class, it is necessary to establish its uniqueness in the Java Virtual machine with the class loader that loads it, and each class loader has a separate class space. As long as the class loader of the load class is different, the two classes must be unequal (including the Equals () method, the Instanceof () method). At this point, there are two classloadertest in the virtual machine, one is loaded by the System Application class loader, and the other is loaded by our defined ClassLoader. A simple example: note the application of getResourceAsStream: Class.getresourceasstream (String Path): path does not start with "/" By default is to fetch resources from the package where it is located, with "/" The beginning is obtained from the classpath root, which is the bin start.

public class Classloadertest {public

	static void Main (string[] args) throws Instantiationexception, Illegalaccessexception, classnotfoundexception {
		ClassLoader myloader = new ClassLoader () {
			@Override
			Public class<?> loadclass (string name) throws ClassNotFoundException {
				try {
					string className = Name.substring (Name.lastindexof (".") + 1) + ". Class";
					
					Returns the input stream reading the specified resource
					inputstream is = GetClass (). getResourceAsStream (className);
					if (is = = null) return Super.loadclass (name);
					Byte[] B = new byte[is.available ()];
					Is.read (b);
					
					Converts a byte array to an instance of class classes return
					defineclass (name, b, 0, b.length);
				} catch (IOException e) {
					throw new ClassNotFoundException (name);}}
		;
		
		Object = Myloader.loadclass ("Test". Classloadertest "). newinstance ();
		System.out.println (Object.getclass ());
		System.out.println (Object instanceof test. classloadertest);
	}


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.