Table of Contents
What is reflection?
Java reflection?
Reflectio
Dynamic Language
Introduction to Java Reflection API
Class object
Generating objects
Home Java Javagetting Started What is reflection in java

What is reflection in java

Apr 13, 2021 pm 05:34 PM
java reflection

In Java, reflection mainly refers to the ability of a program to access, detect and modify its own state or behavior. The main functions of the Java reflection mechanism: 1. Determine the class to which any object belongs at runtime; 2. Construct an object of any class at runtime; 3. Call the method of any object at runtime, etc.

What is reflection in java

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

What is reflection?

Mainly refers to the ability of a program to access, detect and modify its own state or behavior

Java reflection?

In the Java runtime environment, for any class, can you know what properties and methods this class has? For any object, can any of its methods be called?

The Java reflection mechanism mainly provides the following functions:

* 1. Determine the class to which any object belongs at runtime.

 * 2. Construct an object of any class at runtime.

* 3. Determine the member variables and methods of any class at runtime.

 * 4. Call the method of any object at runtime.

Reflectio

Reflection is a key property of Java being regarded 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 the Reflection APIs at runtime.

Includes all information about its modifiers (such as public, static, etc.), superclass (such as Object), implemented interfaces (such as Serializable), and its fields and methods, and can change the contents of fields at runtime Or call methods.

Dynamic Language

The definition of dynamic language "When a program is running, it is allowed to change the program structure or variable type. This language is called a dynamic language."

From this point of view, Perl, Python, and Ruby are dynamic languages, while C, Java, and C# are not dynamic languages.

Although Java is not a dynamic language under this definition and classification, it does have a very prominent dynamic related mechanism: Reflection. This word means: reflection, image, reflection. When used in Java, it means that we can load, detect, and use classes at runtime that are completely unknown during compilation.

In other words, a Java program can load a class whose name is known only at runtime, learn its complete structure (but not including method definitions), and generate its object entities, or set values ​​for its fields, or Evoke its methods.

The ability of the program to examine itself is called introspection. Reflection and introspection are two terms that are often mentioned together.

Introduction to Java Reflection API

In the JDK, the Java reflection mechanism is mainly implemented by the following classes. These classes (except the first one) are all located in java.lang.

in the reflect package Class class: represents a class and is located under the java.lang package.

Field class: represents the member variables of the class (member variables are also called attributes of the class).

Method class: represents the method of the class.

Constructor class: represents the construction method of the class.

Array class: Provides static methods for dynamically creating arrays and accessing array elements.

Class object

To use reflection, you first need to obtain the Class object corresponding to the class to be operated on.

In Java, no matter how many objects of a certain class are generated, these objects will correspond to the same Class object.

This Class object is generated by the JVM, through which the structure of the entire class can be learned.

Three commonly used ways to obtain Class objects:

1. Use the static method of the Class class. For example:

Class.forName(“java.lang.String”);

2. Use the .class syntax of the class. Such as:

String.class;

3. Use the getClass() method of the object. Such as:

String str = “aa”; 
Class

Routine 1: Get the method

The routine DumpMethods class demonstrates the basic function of the Reflection API, which reads the command line The class name specified by the parameter, and then prints the method information of this class.

import java.lang.reflect.Method;
 
public class DumpMethods
{
    public static void main(String[] args) throws Exception //在方法后加上这句,异常就消失了
    {
        //获得字符串所标识的类的class对象
        Class<?> classType = Class.forName("java.lang.String");//在此处传入字符串指定类名,所以参数获取可以是一个运行期的行为,可以用args[0]
 
        //返回class对象所对应的类或接口中,所声明的所有方法的数组(包括私有方法)
        Method[] methods = classType.getDeclaredMethods();
 
        //遍历输出所有方法声明
        for(Method method : methods)
        {
            System.out.println(method);
        }
    }
 
}

Routine 2: Calling the method through reflection

Call the method through reflection. See the code and comments for details:

import java.lang.reflect.Method;
 
public class InvokeTester
{
    public int add(int param1, int param2)
    {
        return param1 + param2;
 
    }
 
    public String echo(String message)
    {
        return "Hello: " + message;
    }
 
    public static void main(String[] args) throws Exception
    {
 
        // 以前的常规执行手段
        InvokeTester tester = new InvokeTester();
        System.out.println(tester.add(1, 2));
        System.out.println(tester.echo("Tom"));
        System.out.println("---------------------------");
 
        // 通过反射的方式
 
        // 第一步,获取Class对象
        // 前面用的方法是:Class.forName()方法获取
        // 这里用第二种方法,类名.class
        Class<?> classType = InvokeTester.class;
 
        // 生成新的对象:用newInstance()方法
        Object invokeTester = classType.newInstance();
        System.out.println(invokeTester instanceof InvokeTester); // 输出true
 
        // 通过反射调用方法
        // 首先需要获得与该方法对应的Method对象
        Method addMethod = classType.getMethod("add", new Class[] { int.class,
                int.class });
        // 第一个参数是方法名,第二个参数是这个方法所需要的参数的Class对象的数组
 
        // 调用目标方法
        Object result = addMethod.invoke(invokeTester, new Object[] { 1, 2 });
        System.out.println(result); // 此时result是Integer类型
 
        //调用第二个方法
        Method echoMethod = classType.getDeclaredMethod("echo", new Class[]{String.class});
        Object result2 = echoMethod.invoke(invokeTester, new Object[]{"Tom"});
        System.out.println(result2);
 
    }
}

Generating objects

If you want to generate objects through the constructor method of a class without parameters, we have two ways:

1. Obtain the Class object first, and then directly generate it through the newInstance() method of the Class object:

 Class<?> classType = String.class;
 
 Object obj = classType.newInstance();

2. Obtain the Class object first, and then obtain the corresponding Constructor object through the object. Then generate

through the newInstance() method of the Constructor object (where Customer is a custom class with a parameterless constructor and a parameterized constructor):

    Class<?> classType = Customer.class;
 
    // 获得Constructor对象,此处获取第一个无参数的构造方法的
    Constructor cons = classType.getConstructor(new Class[] {});
 
    // 通过构造方法来生成一个对象
    Object obj = cons.newInstance(new Object[] {});

If you want to generate an object through the parameterized constructor of a class, you can only use the following method:

(Customer is a custom class with a parameterless constructor and a parameterized constructor. Method, pass in strings and integers)

    Class<?> classType = Customer.class;
 
    Constructor cons2 = classType.getConstructor(new Class[] {String.class, int.class});
 
    Object obj2 = cons2.newInstance(new Object[] {"ZhangSan",20});

可以看出调用构造方法生成对象的方法和调用一般方法的类似,不同的是从Class对象获取Constructor对象时不需要指定名字,而获取Method对象时需要指定名字。

相关视频教程推荐:Java视频教程

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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Java Persistence with Spring Data JPA and Hibernate Java Persistence with Spring Data JPA and Hibernate Aug 22, 2025 am 07:52 AM

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

LOL Game Settings Not Saving After Closing [FIXED] LOL Game Settings Not Saving After Closing [FIXED] Aug 24, 2025 am 03:17 AM

IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.

How to use the Pattern and Matcher classes in Java? How to use the Pattern and Matcher classes in Java? Aug 22, 2025 am 09:57 AM

The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient

Edit bookmarks in chrome Edit bookmarks in chrome Aug 27, 2025 am 12:03 AM

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.

'Java is not recognized' Error in CMD [3 Simple Steps] 'Java is not recognized' Error in CMD [3 Simple Steps] Aug 23, 2025 am 01:50 AM

IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.

See all articles