Several ways to get class in Java

Source: Internet
Author: User

Take Hello.class as an example

 Public class Hello {    publicstaticvoid  main (string[] args) {        // TODO auto-generated Method stub        System.out.println ("tes22t2");          for (String Arg:args)        {            System.out.println ("Hello Proms:" + arg);     }}}

1. Reflection

 Public Static voidMain (string[] args)throwsException {args=Newstring[]{"Hello", "Java Madness handout W"}; String Progclass= Args[0]; String[] Progargs=NewString[args.length-1]; System.arraycopy (args,1, Progargs, 0, progargs.length);//url[] urls = {new URL ("File:")};//class<?> clazz = (new URLClassLoader (URLs)). LoadClass (Progclass);        class<?> clazz = Class.forName (Progclass); //get the main method of the class you want to runMethod main = Clazz.getmethod ("Main", (NewString[0]). GetClass ()); Object[] Argsarray={Progargs}; Main.invoke (NULL, Argsarray); }

2.URLClassLoader

url[] URLs = {new URL ("File:")}; Class<?> clazz = (new URLClassLoader (URLs)). LoadClass (Progclass);

3.loadClass

Compileclassloader CCL = new Compileclassloader ();//Load the class to be run class<?> clazz = Ccl.loadclass (Progclass);

4. Overwrite Findclass

Reference

java8--class loading mechanism and reflection (Java Madness Handout 3 Review notes)

Several ways to get class in Java

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.