search
HomeJavajavaTutorialWhat is the meaning and role of reflection in Java?

1. Overview of Reflection

Reflection (reflection) is the key to being regarded as a dynamic language. The reflection mechanism allows the program to obtain the internal information of any class through the Reflection API during execution, and can directly operate any object. internal properties and methods. After the class is loaded, a Class type object is generated in the method area of ​​the heap memory (a class has only one Class object). This object contains the complete structural information of the class. We can see the structure of the class through this object. This object is like a mirror. We can see the structure of the class through this mirror, so we vividly call it reflection.

2. Commonly used api

java.lang.Class: represents a class

java.lang.reflect.Method : Represents the method of the class

java.lang.reflect.Field: Represents the member variable of the class

java.lang.reflect.Constructor: Constructor representing the class

static Class forName(String name) Returns the Class object of the specified class name name

Object newInstance() Call None Parameter constructor, return an instance of the Class object

getName() Return the name of the entity (class, interface, array class, basic type or void) represented by this Class object

Class getSuperClass() Returns the Class object of the parent class of the current Class object

Class [] getInterfaces() Gets the interface of the current Class object

ClassLoader getClassLoader() Returns the class loader of this class

Class getSuperclass() Returns the Class that represents the super class of the entity represented by this Class

Constructor[] getConstructors() Returns an array containing certain Constructor objects

Field[] getDeclaredFields() Returns an array of Field objects ArrayMethod

getMethod(String name,Class … paramTypes) Returns a Method object, the formal parameter type of this object is paramType

Example:

public class Person {
    private String name;
    private int age;
    public Person() {
        System.out.println("Person类被初始化了。。。。。^_^");
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }
}

Reflection

public class ClassDemo {
    public static void main(String[] args) throws
        Exception {
        // 1. 创建Class对象
        //Class<person> clazz = (Class<person>)
        Class.forName("Person");
        Class> clazz =Class.forName("Person");
            // 2. 通过Class对象调用其方法
            // 2.1. 通过反射来实例化对象
            //Person person = clazz.newInstance();
            Object o = clazz.newInstance(); // 此名就相当于
        Person p = new Person()
            // 2.2. 获取类的完整类名称(包名+类名)
            String name = clazz.getName();
        System.out.println(name);
        // 2.3. 获取类的简单名称,就是类的名称,不含包名
        System.out.println(clazz.getSimpleName());
        // 2.4. 获取构造器
        Constructor>[] constructors =
            clazz.getConstructors();
        for (Constructor> constructor :
             constructors) {
            System.out.println(constructor.getName());
        }
        // 2.5. 获取字段
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }
        // 2.6. 获取方法
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
        }
    }
}</person></person>

3. Four ways to create Class objects

public class Demo {
    public static void main(String[] args) throws
        Exception {
        // 第一种方式:调用Class.forName()
        Class clazz =Class.forName("java.lang.String");
        // 第二种方式:通过类的字节码文件来创建
        Class clazz1 = String.class;
        // 第三种方式:通过调用对象的getClass()方法来创建
        String str = new String();
        Class clazz2 = str.getClass();
        // 第四种:通过类装载器来创建
        ClassLoader loader =String.class.getClassLoader();
        Class> clazz3 =loader.loadClass("java.lang.String");
    }
}

The above is the detailed content of What is the meaning and role of reflection in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools