Reflection loading class

Source: Internet
Author: User

Reflection loading class

Reflection: java. lang. reflect

Classes to be loaded:

package eg.fortest;public class WaitingforLoader {private String str;static{System.out.println("loading WaitingforLoader");}public WaitingforLoader() {str="empty";System.out.println("Constructor of WaitingforLoader without anything.");}public WaitingforLoader(String str) {this.str=str;System.out.println("Constructor of WaitingforLoader with "+str);}public void getStr(int i){System.out.println("str="+str);}}

Load the running class:

Package factory. classfactory; import java. lang. reflect. constructor; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; // import eg. fortest. waitingforLoader; public class LoadMyClass {public static void main (String [] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, expiration , InvocationTargetException {System. out. println ("Program start.");/*** class loading, linking, and initialization. */Class <?> Clazz = Class. forName ("eg. fortest. waitingforLoader ");/*** Object creation */Object myvar1 = clazz. newInstance (); Constructor cor = clazz. getConstructor (String. class); Object myvar2 = cor. newInstance ("string Parameter");/*** Method call */Method m = clazz. getMethod ("getStr", int. class); m. invoke (myvar2, 1 );}}

Output result:

Program start.
Loading WaitingforLoader
Constructor of WaitingforLoader without anything.
Constructor of WaitingforLoader with string Parameter
Str = string Parameter

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.