Basic concepts of Java Reflection

Source: Internet
Author: User

0. Instance Preparation

 PackageCom.blueStarWei.invoke; Public classStudent {PrivateString name;  PublicStudent () {} PublicStudent (String name) {Super();  This. Name =name; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetName () {returnname; } @Override PublicString toString () {return"Student [name=" + name + "]"; }}

1. What is Reflection

Reflection is the information (such as interface information, member information, method information, and so on) that gets the type dynamically at run time (not at compile time), and then creates objects, accesses modify members, and invokes methods based on the information obtained.

2. How to get the class (3 types):

// mode one: Class.forName ("package name. Class name") Class stu1 = Class.forName ("com.blueStarWei.invoke.Student"); // Way two: Class name. class Class STU2 = Student. class ; // mode three: instance. GetClass () New Student (). GetClass ();

3. Create an Instance Object

Student Student = (Student) stu.newinstance ();

Note: 1) This method creates an instance by means of a non-parametric construct.

2) When you new an object, the class may not be loaded, and when you use the Newinstance () method, you must ensure that the class is loaded and connected "through Class.forName ()."

Class clazz = Class.forName ("com.blueStarWei.invoke.Student"= (Student) clazz.newinstance (); // equivalent to New Student ();

4. The effect of reflection

4.1 Determine the class to which any object belongs;

4.2 Determine the member variables and methods that any class has;

4.3 Methods for invoking arbitrary objects;

4.4 Constructs an object of any class;

4.5 Generate dynamic agent operations.

Basic concepts of Java Reflection

Related Article

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.