"Turn-and-organize" Java Reflection mechanism

Source: Internet
Author: User
Tags reflection stringbuffer idf

Concept

It is the ability of a program to access, detect and modify its own state or behavior, and to adjust or modify the state and related semantics of the behavior described by the application according to the state and result of its behavior.

Reflection Mechanism effect

1, anti-compilation:. Class-->.java

2, through the reflection mechanism to access Java Object Properties, methods, construction methods, etc.;

Sun provides reflection mechanism classes

Java.lang.Class;

Java.lang.reflect.Constructor;

Java.lang.reflect.Field;

Java.lang.reflect.Method;

Java.lang.reflect.Modifier;

Reflection implementation

1. There are three ways of reflection realization

1 //The first way:2CLASSC1 = Class.forName ("Employee"); 3 //The second way:4 //each type in Java has a class attribute. 5CLASSC2 = Employee.class; 6    7 //The Third Way:8 //any Java object in the Java language has a GetClass method9Employeee =NewEmployee (); TenCLASSC3 = E.getclass ();//C3 is the runtime class (the run-time class for E is employee)

2. After getting the class, use Newinstance to create the object

1 Class C =class.forname ("Employee");   2   3 // Create a new instance  of the class represented by this class object 4 // an employee's parameterless construction method was called.  

3. Get Properties

① Get all Properties

  

1 //get the entire class2Class C = class.forname ("Java.lang.Integer"); 3               //get all the properties? 4field[] fs =C.getdeclaredfields (); 5        6                    //defines a variable-length string used to store properties7StringBuffer SB =NewStringBuffer (); 8             //stitching each property into this string by appending the method9             //the outermost public definitionTenSb.append (Modifier.tostring (C.getmodifiers ()) + "class" + c.getsimplename () + "{\ n");  One             //each of the properties inside A              for(Field field:fs) { -Sb.append ("\ t");//Space -Sb.append (Modifier.tostring (Field.getmodifiers ()) + "");//gets the modifier for the property, such as Public,static, and so on theSb.append (Field.gettype (). Getsimplename () + "");//the name of the type of the property -Sb.append (Field.getname () + "; \ n");//Name of property + carriage return -             }   -        +Sb.append ("}");  -        +System.out.println (SB);

② get the specified property

  

1  Public Static voidMain (string[] args)throwsexception{2               3<span style= "White-space:pre" > </span>//the previous way:4     /* 5 User U = new user ();6 u.age = n;//set7 System.out.println (u.age);//get8     */  9               Ten     //Get class OneClass C = class.forname ("User");  A     //Get ID Property -Field IdF = C.getdeclaredfield ("id");  -     //instantiate this class to assign O theObject o =c.newinstance ();  -     //Break Package -Idf.setaccessible (true);//using the reflection mechanism can break the encapsulation and cause the properties of the Java object to be unsafe.  -     //assigns the id attribute of the O object to "Max" +Idf.set (O, "110");//Set -     //Get + System.out.println (Idf.get (o));  A}

4, Get methods, and construction methods, no longer described in detail, just look at the keyword:

Method keyword

Meaning

Getdeclaredmethods()

Get all the methods

Getreturntype()

Get the return type of the method

Getparametertypes()

Get the incoming parameter type for a method

Getdeclaredmethod ("Method name", Parameter type. Class,......)

Get a specific approach

Constructor method keyword

Meaning

Getdeclaredconstructors()

Get all the construction methods

Getdeclaredconstructor (parameter type. Class,......)

Get a specific construction method

Parent class and Parent interface

Meaning

Getsuperclass()

Gets the parent class of a class

Getinterfaces()

Get an interface for a class implementation

"Turn-and-organize" Java Reflection mechanism

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.