Detailed explanation of examples of reflection mechanism in Java
This article mainly introduces relevant information about Java reflection mechanism examples. Here is a detailed analysis of the reflection mechanism in Java. Friends in need can refer to
Java Reflection Mechanism Detailed Examples.
1. Is JAVA a dynamic language?
Generally speaking, when it comes to dynamic languages, it means that the program structure or variable type is allowed to be changed while the program is running. From this point of view, Java, like C++, is not a dynamic language.
But JAVA has a very prominent dynamic related mechanism: reflection. Through reflection, Java can load, detect and use classes that were fully summed during compilation at runtime, generate their object entities, call their methods or set values for properties. So Java is considered a semi-dynamic language.
The concept of reflection:
The reflection mechanism in Java means that in the running state, for any class, all properties and methods of this class can be known;
For any object, any of its methods can be called;
This function of dynamically obtaining information and dynamically calling object methods is called the reflection mechanism of the Java language
II , Dynamic properties
##2.1. Dynamic properties
Generate object instances during runtime;Call methods during runtime;
Change attributes during runtime
2.2. Functions that can be achieved by the Java reflection mechanism
Judge the class to which any object belongs at runtimeConstruct the class of any class at runtime Object
Judge the methods and attributes of any class at runtime
Call the method of any object at runtime
Generate a dynamic proxy
Many objects in Java programs will have two types at runtime: compile-time type and run-time type
The compile-time type is determined by the time when the object is declared. The type used is determined by the type used. The type at runtime is determined by the type actually assigned to the object.
For example:
Person p =new Student();
The compile-time type is Person, and the run-time type is Person. For Student
In addition, the program may also receive an object passed in from the outside during runtime. The compile-time type of the object is Object, but the program needs to call the method of the runtime type of the object. To solve these problems, programs need to discover real information about objects and classes at runtime. However, if it is impossible to predict which classes the object and class may belong to at compile time, and the program only relies on runtime information to discover the real information of the object and class, reflection must be used at this time
3. Java Reflection APIThe reflection API is used to generate information about classes, interfaces or objects in the current JAVA virtual machine.
Class class: The core class of reflection, which can obtain the attributes, methods and other content information of the class.
Field class: Java.lang.reflect. Represents the attributes of the class, and can get and set the attribute values of the class.Method class:Java.lang.reflect. Represents a method of a class, which can be used to obtain information about methods in a class or execute methods
Construcor class: Java.lang.reflect. Represents the constructor method of the class.
Person class
package com.pb.Reflect.classinfo; public class Person { private String name; private String gender; private int age; private Person() { // } public Person(String name, String gender, int age) { super(); this.name = name; this.gender = gender; this.age = age; } //getter、和setter方法 private String getName() { return name; } private void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "姓名:"+name+"年龄: "+age; } }
Use reflection:
package com.pb.Reflect.classinfo; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import javax.swing.JOptionPane; /* * 通过用户输入类的全路径,来获取该类的成员方法和属性 * Declared获取全部不管是私有和公有 * 1.获取访问类的Class对象 * 2.调用Class对象的方法返回访问类的方法和属性信息 */ public class ReflectDemo { /* * 构造方法 */ public ReflectDemo(){ //用户输入类的全路径径 //使用String组件 String classpsth=JOptionPane.showInputDialog(null,"输入类的全路径"); //使用Class.forName方法根据输入的类的全路径 返回该类的Class对象 try { Class cla = Class.forName(classpsth); //利用Class对象的cla的自审,返回方法对象集合 Method [] method=cla.getDeclaredMethods(); //返回所有的方法 System.out.println("========获取方法信息============"); for (Method meth : method) { //遍历method数组,并输出方法信息 System.out.println(meth.toString()); } System.out.println("========获取出方法信息结束============"); //获取属性利用Class对象的cla的自审,返回成员属性对象集合 Field [] field=cla.getDeclaredFields(); System.out.println("========获取成员属性信息============"); for (Field f : field) { System.out.println(f.toString()); } System.out.println("========获取成员属性信息结束============"); //获取属性利用Class对象的cla的自审,返回构造方法集合 Constructor [] constructor=cla.getDeclaredConstructors(); System.out.println("========获取成员构造方法信息============"); for (Constructor constru : constructor) { System.out.println(constru.toString()); } System.out.println("========获取成员构造方法信息结束============"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("路径输入错误!"); } } }
package com.pb.Reflect.classinfo; public class TestReflection { public static void main(String[] args) { ReflectDemo rd=new ReflectDemo(); } }
Enter com.pb.Reflect.classinfo.Person
Result:
========获取方法信息============ public java.lang.String com.pb.Reflect.classinfo.Person.getGender() public void com.pb.Reflect.classinfo.Person.setGender(java.lang.String) public int com.pb.Reflect.classinfo.Person.getAge() public void com.pb.Reflect.classinfo.Person.setAge(int) public java.lang.String com.pb.Reflect.classinfo.Person.toString() private java.lang.String com.pb.Reflect.classinfo.Person.getName() private void com.pb.Reflect.classinfo.Person.setName(java.lang.String) ========获取出方法信息结束============ ========获取成员属性信息============ private java.lang.String com.pb.Reflect.classinfo.Person.name private java.lang.String com.pb.Reflect.classinfo.Person.gender private int com.pb.Reflect.classinfo.Person.age ========获取成员属性信息结束============ ========获取构造方法信息============ private com.pb.Reflect.classinfo.Person() public com.pb.Reflect.classinfo.Person(java.lang.String,java.lang.String,int) ========获取构造方法信息结束============
5. Steps to use reflection
5.1. Steps
Java.lang.reflect
Get the Java.lang.Class object of the class you want to operate
Call the method of ClassUse the reflection API to operate this information
Call the getClass() method of an object
Person p = new Person(); Class cla=p.getClass();
Call the class attribute of a certain class to obtain the Class object corresponding to the class
Class cls=Person.class;
Use the forName() static method of the Class class
Class cla=Class.forName(“类的全路径”);
6. The second method is the getClass() method of the object
Person class. Because the object is to be declared, the constructor method public
package com.pb.Reflect.classinfo; public class Person { private String name; private String gender; private int age; public Person() { // } public Person(String name, String gender, int age) { super(); this.name = name; this.gender = gender; this.age = age; } //getter、和setter方法 private String getName() { return name; } private void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "姓名:"+name+"年龄: "+age; } }
uses reflection:
package com.pb.Reflect.classinfo; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import javax.swing.JOptionPane; /* * 通过用户输入类的全路径,来获取该类的成员方法和属性 * Declared获取全部不管是私有和公有 * 1.获取访问类的Class对象 * 2.调用Class对象的方法返回访问类的方法和属性信息 */ public ReflectDemo(Person p){ Class cla=p.getClass(); //利用Class对象的cla的自审,返回方法对象集合 Method [] method=cla.getDeclaredMethods(); //返回所有的方法 System.out.println("========获取方法信息============"); for (Method meth : method) { //遍历method数组,并输出方法信息 System.out.println(meth.toString()); } System.out.println("========获取出方法信息结束============"); //获取属性利用Class对象的cla的自审,返回成员属性对象集合 Field [] field=cla.getDeclaredFields(); System.out.println("========获取成员属性信息============"); for (Field f : field) { System.out.println(f.toString()); } System.out.println("========获取成员属性信息结束============"); //获取属性利用Class对象的cla的自审,返回构造方法集合 Constructor [] constructor=cla.getDeclaredConstructors(); System.out.println("========获取成员构造方法信息============"); for (Constructor constru : constructor) { System.out.println(constru.toString()); } System.out.println("========获取成员构造方法信息结束============"); } }
Test Class
package com.pb.Reflect.classinfo; public class TestReflection { public static void main(String[] args) { Person p=new Person(); ReflectDemo rd=new ReflectDemo(p); } }
========获取方法信息============ public java.lang.String com.pb.Reflect.classinfo.Person.getGender() public void com.pb.Reflect.classinfo.Person.setGender(java.lang.String) public int com.pb.Reflect.classinfo.Person.getAge() public void com.pb.Reflect.classinfo.Person.setAge(int) public java.lang.String com.pb.Reflect.classinfo.Person.toString() private java.lang.String com.pb.Reflect.classinfo.Person.getName() private void com.pb.Reflect.classinfo.Person.setName(java.lang.String) ========获取出方法信息结束============ ========获取成员属性信息============ private java.lang.String com.pb.Reflect.classinfo.Person.name private java.lang.String com.pb.Reflect.classinfo.Person.gender private int com.pb.Reflect.classinfo.Person.age ========获取成员属性信息结束============ ========获取成员构造方法信息============ public com.pb.Reflect.classinfo.Person() public com.pb.Reflect.classinfo.Person(java.lang.String,java.lang.String,int) ========获取成员构造方法信息结束============
7. Chapter The .class attributes of the three method classes
Person class is the same as above
Test class:
package com.pb.Reflect.classinfo; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class TestReflection { public static void main(String[] args) { /*第二种方法 Person p=new Person(); ReflectDemo rd=new ReflectDemo(p); */ /* * 第三种方式.class属性 */ Class cla=Person.class; //利用Class对象的cla的自审,返回方法对象集合 Method [] method=cla.getDeclaredMethods(); //返回所有的方法 System.out.println("========获取方法信息============"); for (Method meth : method) { //遍历method数组,并输出方法信息 System.out.println(meth.toString()); } System.out.println("========获取出方法信息结束============"); //获取属性利用Class对象的cla的自审,返回成员属性对象集合 Field [] field=cla.getDeclaredFields(); System.out.println("========获取成员属性信息============"); for (Field f : field) { System.out.println(f.toString()); } System.out.println("========获取成员属性信息结束============"); //获取属性利用Class对象的cla的自审,返回构造方法集合 Constructor [] constructor=cla.getDeclaredConstructors(); System.out.println("========获取成员构造方法信息============"); for (Constructor constru : constructor) { System.out.println(constru.toString()); } System.out.println("========获取成员构造方法信息结束============"); } }
Result:
Same as above
========获取方法信息============ public java.lang.String com.pb.Reflect.classinfo.Person.getGender() public void com.pb.Reflect.classinfo.Person.setGender(java.lang.String) public int com.pb.Reflect.classinfo.Person.getAge() public void com.pb.Reflect.classinfo.Person.setAge(int) public java.lang.String com.pb.Reflect.classinfo.Person.toString() private java.lang.String com.pb.Reflect.classinfo.Person.getName() private void com.pb.Reflect.classinfo.Person.setName(java.lang.String) ========获取出方法信息结束============ ========获取成员属性信息============ private java.lang.String com.pb.Reflect.classinfo.Person.name private java.lang.String com.pb.Reflect.classinfo.Person.gender private int com.pb.Reflect.classinfo.Person.age ========获取成员属性信息结束============ ========获取成员构造方法信息============ public com.pb.Reflect.classinfo.Person() public com.pb.Reflect.classinfo.Person(java.lang.String,java.lang.String,int) ========获取成员构造方法信息结束============
The above is the detailed content of Detailed explanation of examples of reflection mechanism in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
