Java loads classes through classloader and then instantiates classes through classforname

Source: Internet
Author: User

 

Write a Web server by yourself and find that class. forname cannot be used and the class cannot be found because the class path cannot be found,

 

YesLoad the file path of the required class, and then use classloader to load the required class. The original

 

I will not say much about it.Code:

 

URL url = new URL ("Path of the folder where the class is located");
String classname = "Name of the class to be loaded ";
Classloader Cl = new urlclassloader (new URL [] {URL });
Class D = Cl. loadclass (classname );

// Instantiate the loaded class
Object action = Class. forname (classname). newinstance ();
Method method =Action. Getclass (). getmethod ("classname class method", parameter type );
Method. Invoke (Action, Parameter );

The following is the code snippet:

URL url = new URL ("file: \ D: \ Users \ Administrator \ workspaces \ myeclipse 8.6 \ SRC "); string name = "visit"; classloader Cl = new urlclassloader (new URL [] {URL}); Class classname = Cl. loadclass (name); system. out. println ("d ------------------" + classname); system. out. println ("Cl ----------------------" + Cl); Action = Class. forname ("visit "). newinstance (); Method method = action. getclass (). getmethod ("Showa"); method. invoke (action );

 

 

 

 

 

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.