JAVA reflection mechanism learning notes (2), java learning notes

Source: Internet
Author: User

JAVA reflection mechanism learning notes (2), java learning notes

The last time I wrote a learning note on the reflection mechanism of JAVA (I), I was busy these days in July 22, and my pace was totally disrupted ~ You cannot continue to be passive. You have to find your own pace again.

4. Obtain the Constructor of the class


Obtain the constructor of a class through the reflection mechanism, and then call the constructor to create an instance of the class.

The Class <T> Class provides several methods to obtain the Class constructor.

Public Constructor <T> getConstructor (Class <?>... ParameterTypes)

Returns a Constructor object that reflects the specified public Constructor of the Class Object.

Public Constructor <?> [] GetConstructors ()

Returns an array containing certain Constructor objects. These objects reflect all the common Constructor methods of the classes represented by this Class object.

Public Constructor <T> getDeclaredConstructor (Class <?>... ParameterTypes)

Returns a Constructor object that reflects the specified Constructor of the Class object or interface.

Public Constructor <?> [] GetDeclaredConstructors ()

Returns an array of Constructor objects that reflect all Constructor methods of Class declarations represented by this Class object. They are public, protected, default (Package) Access, and private constructor

5. Create a class instance

There are several ways to create a new class instance through the reflection mechanism

Call ctor without independent variable

1. Call the newInstance method of the Class Object of the Class. This method calls the default constructor of the object. If no default constructor exists, the call fails.

Class <?> ClassType = ExtendType. class;

Object inst = classType. newInstance ();

System. out. println (inst );

Output:

Type: Default Constructor

ExtendType: Default Constructor

Com. quincy. ExtendType @ d80be3

 

2. Call the newInstance method of the default Constructor object

Class <?> ClassType = ExtendType. class;

Constructor <?> Constructor1 = classType. getConstructor ();

Object inst = constructor1.newInstance ();

System. out. println (inst );

Output:

Type: Default Constructor

ExtendType: Default Constructor

Com. quincy. ExtendType @ 1006d75

Call the ctor with Parameters

3. Call the newInstance method with the Constructor object

Constructor <?> Constructor2 =

ClassType. getDeclaredConstructor (int. class, String. class );

Object inst = constructor2.newInstance (1, "123 ");

System. out. println (inst );

Output:

Type: Default Constructor

ExtendType: Constructor with parameters

Com. quincy. ExtendType @ 15e83f9

class Dog {    public String name;    public int age;    public int weigh;    public void bark(String name){        System.out.println(name);};    public void run(){};    Dog(){}    Dog(String name) {        this.name = name;    }    Dog(String name,int age) {        this.name = name;        this.age = age;    }}

// Obtain bytecode, Which is safer and more efficient. Class clazzDog = Dog. class; System. out. println ("------------------- Constructor -----------------"); // use ggetDeclaredConstructors to obtain the Constructor. <?> [] Constructors2 = clazzDog. getDeclaredConstructors (); for (Constructor <?> M: constructors2) {System. out. println (m); Class <?> [] Types = m. getParameterTypes (); for (Class <?> Type: types) {System. out. println (type) ;}} System. out. println ("----------------- new instance -------------------"); Constructor constructor = clazzDog. getDeclaredConstructor (String. class, int. class); Dog dog = (Dog) constructor. newInstance ("change", 2); System. out. println (dog. name );

----------------- Constructor ------------------- com. reflection. dog () com. reflection. dog (java. lang. string) class java. lang. stringcom. reflection. dog (java. lang. string, int) class java. lang. stringint ----------------- new instance ------------------- change

6. Call functions of the class

Obtain the class Method object through reflection and call the Field Invoke Method to call the function.

// Obtain bytecode, Which is safer and more efficient. Class clazzDog = Dog. class; Object object = clazzDog. newInstance (); Method = clazzDog. getDeclaredMethod ("bark", String. class); method. invoke (object, "dog name ");
Dog name

7. Set/obtain the class property value

Obtains the Field object of the class through reflection, and calls the Field method to set or obtain the value.

// Obtain bytecode, Which is safer and more efficient. Class clazzDog = Dog. class; Object object = clazzDog. newInstance (); Field field = clazzDog. getDeclaredField ("name"); field. set (object, "Huan HUan"); System. out. println (Dog) object ). name );
Huanhuan





Java reflection mechanism

During Java runtime, can I know the attribute methods of a class and call and modify them? Can an object know its class and call its method? The answer is yes. This kind of dynamic mechanism for obtaining information and calling methods is called "reflection" in Java ).
The Java reflection mechanism mainly provides the following functions:
Determine the class to which any object belongs at runtime;
Construct any class object at runtime;
Judge the member variables and methods of any class at runtime;
Call the methods of any object at runtime.
Reflection is a key feature of Java as a dynamic (or quasi-dynamic) language. This mechanism allows the program to obtain the internal information of any class with a known name through Reflection APIs at runtime, including its modifiers (such as public and static), superclass (such as Object), implements interfaces (such as Serializable), also includes all information about fields and methods, and can change fields content or call methods at runtime.
Generally speaking, when talking about dynamic languages, the developer community roughly agrees with the definition: "When a program is running, the program structure or variable type can be changed. This language is called dynamic language ".
In JDK, the following classes are used to implement the Java reflection mechanism. These classes are located in the java. lang. reflect package:
Class: represents a Class;
Field Class: represents the member variables of the class (member variables are also called the attributes of the class );
Method class: indicates the Method of the class;
Constructor class: Constructor class;
Array class: provides static methods for dynamically creating arrays and accessing Array elements;

For more information, see references. I think this document is good.
Reference: 2.16.hi.baidu.com/#/detail/24992875

Java Reflection (JAVA Reflection) Mechanism

I started to score again. Is it interesting?

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.