A very easy Java Reflection tutorial

Source: Internet
Author: User

Original articles, reproduced please specify.


Reflection can dynamically load classes, instantiate objects, and invoke methods. Now the following example explains.

One. Load class.

Class clazz = Class.forName ("java.lang.String"); This sentence code gets the class object of a string class.

Enter the name of the package.

If through URLClassLoader. Capable of loading local or remote jar packages. And the detailed class object is obtained by the LoadClass method.

Second, instantiate the object.

Assuming that the object is instantiated through the default constructor, we can get an object such as the following method for the class object, such as

Clazz. Newinstance ();

Assuming that an object is instantiated through a constructor with a number of parameters, it can be achieved by, for example, the following code:

constructor<?

> myconstructor = Myclass.getconstructor (parametertypes);//Get a constructor object.

Among them parametertypes for class<?

Parametertypes. Like String.class,int.class and so on. The object is then instantiated through the constructor object:

Myconstructor.newinstance ("xxx", 123); The constructor fills in the detailed construction parameters.

Three. Invokes a method.

Method Mezod = Clazz.getmethod (MethodName, parametertypes), can get the object of the methods class, then we can run the method through the Mezod invoke method.

Mezod.invoke (obj, "xxx", 123);//The first parameter is the initiator of this method, and if NULL is used, it means that the statically static method is called.

A very easy Java Reflection tutorial

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.