Table of Contents
1. What is reflection
2. The role of reflection
Since any class is a subclass of Object and there is getClass in Object, you can obtain
 After obtaining the
It is divided into all attributes and specified attributes
Create a test object:
Set the value of the attribute through reflection, distinguishing attributes Modification range, private cannot be set directly
The reflection mechanism is in the
Class
object, use it to create an object, call the no-argument constructor through newInstance() to create the object, and newInstance() returns An Object:
3.4.1. Obtaining all attributes
Get the modifications
3.4.2 获取指定属性
传统属性的获取和通过反射获取对比:
Home Java javaTutorial Reflection basics of java

Reflection basics of java

Feb 24, 2017 am 09:51 AM
java


1. What is reflection


The reflection mechanism is in the running state, for any Class, you can know all the methods and attributes of this class; for any object, you can call any of its methods and attributes. This information and dynamically call the object's method is called Java's reflection mechanism.

2. The role of reflection

  • 1. Decompilation: .class–>java

  • ##2 , Access the properties, methods, constructors, etc. of objects through the reflection mechanism

3. Specific implementation of reflection

3. 1 Reflection-related classes

  • java.lang.Class;

  • java.lang.reflect.Constructor;

  • java.lang.reflect .Field;

  • java.lang.reflect.Method;

  • ##java.lang.reflect.Modifier;
  • 3.2 Three ways to obtain large Class objects

Since any class is a subclass of Object and there is getClass in Object, you can obtain

Class objects - public final native Class<?> getClass();
-

package com.chb.reflectTest;public class Test {
    public static void main(String[] args) throws Exception {        //第一种方式:
        Class<?> c1 = Class.forName("com.chb.reflectTest.Test");    //第二种方式:java中每个类都有class属性
        Class<?> c2 = Test.class;        //第三种方式:每个对象都与getClass()方法
        Class<?> c3 = new Test().getClass();
    }
}
Copy after login

3.3 Create an object

 After obtaining the

Class

object, use it to create an object, call the no-argument constructor through newInstance() to create the object, newInstance() returns An Object:

Class<?> c1 = Class.forName("com.chb.reflectTest.Test");Object o1 = c1.newInstance();
Copy after login
Copy after login
3.4. Obtaining data

It is divided into all attributes and specified attributes

3.4.1. Obtaining all attributes

    Get the modifications
    • First get the modification object through getModifiers() of the attribute,
    • Then through java.long. reflect.Modifier's toString() prints classes and attribute modifications (public, static, final, etc.).
    Get attributes
    • Get all attributes: Return a Fielded array* through getDeclaedFields() of the Class object *.
    Get the type of attribute:
    • Through getType() of the attribute object (Field object)
    • Class<?> cString = Class.forName("java.lang.String");
              //获取累的修饰和名称
              System.out.print(Modifier.toString(cString.getModifiers())+" class " + cString.getSimpleName()+"{\n");
              //获取所有属性
              Field[] fields = cString.getDeclaredFields();
              for (Field field : fields) {
                  System.out.print("\t");
                  System.out.print(
                          Modifier.toString(field.getModifiers())+" "//属性的修饰
                        + field.getType().getSimpleName()+" "
                        + field.getName()+"\n");           
              }
              System.out.println("}");
      Copy after login
      Copy after login
    3.4.2 Get the specified attribute

Create a test object:

Note: I defined two attributes in the Use class, one public, A private, for the next test reflection can break the encapsulation

package com.chb.reflectTest;public class User {    
private String name;    
public  String nickName;    
public User() {}    
public User(String name, String nickName) {        
this.name = name;        
this.nickName = nickName;
    }
    setter getter...

}
Copy after login
Copy after login
Comparison between traditional attribute acquisition and acquisition through reflection:

package com.chb.reflectTest;import java.lang.reflect.Field;public class Test1 {
    public static void main(String[] args) throws Exception {
        //传统获取属性的值
        //1、通过getter,setter
        User user1 = new User();
        user1.setName("lisi");
        System.out.println(user1.getName());
        //2、直接调用属性
        User user2 = new User();
        user2.nickName = "癞皮狗";
        System.out.println(user2.nickName);
        //=========================================
        //通过反射来设置,获取属性。
        Class<User> c1 = (Class<User>) Class.forName("com.chb.reflectTest.User");
        User user = c1.newInstance();
        Field nickField = c1.getDeclaredField("nickName");
        nickField.set(user, "123");
        System.out.println(nickField.get(user));

        Field nameFiled = c1.getDeclaredField("name");
        //Exception in thread "main" java.lang.IllegalAccessException: 
        Class com.chb.reflectTest.Test1 can not access a member of class com.chb.reflectTest.User with modifiers "private"
        nameFiled.setAccessible(true);
        nameFiled.set(user, "oup");
        System.out.println(nameFiled.get(user));

    }
}
Copy after login
Copy after login

Set the value of the attribute through reflection, distinguishing attributes Modification range, private cannot be set directly

An access error will occur, which is the safe access mechanism of java, error message:

Exception in thread "main" java.lang.IllegalAccessException: Class com.chb.reflectTest.Test1 can not access a member of class com.chb.reflectTest.
User with modifiers "private"
Copy after login
Copy after login

We use a method to break the encapsulation of java:

nameFiled.setAccessible(true);
Copy after login
Copy after login

1. What is reflection?

The reflection mechanism is in the

running state

. For any class, you can know all the methods and attributes of this class; for any object , you can call any of its methods and attributes. This information and dynamically calling the object method are called Java's reflection mechanism. 2. The role of reflection

    1. Decompilation: .class–>java
  • ##2 , Access the properties, methods, constructors, etc. of objects through the reflection mechanism
  • 3. Specific implementation of reflection
3. 1 Reflection-related classes

java.lang.Class;
  • java.lang.reflect.Constructor;
  • java.lang.reflect .Field;
  • java.lang.reflect.Method;
  • ##java.lang.reflect.Modifier;

  • 3.2 Three ways to obtain large Class objects

  • Since any class is a subclass of Object and there is getClass in Object, you can obtain

Class

objects - public final native Class<?> getClass(); -

package com.chb.reflectTest;public class Test {
    public static void main(String[] args) throws Exception {        //第一种方式:
        Class<?> c1 = Class.forName("com.chb.reflectTest.Test");        //第二种方式:java中每个类都有class属性
        Class<?> c2 = Test.class;        //第三种方式:每个对象都与getClass()方法
        Class<?> c3 = new Test().getClass();
    }
}
Copy after login
3.3 Create an object
 After obtaining the

Class

object, use it to create an object, call the no-argument constructor through newInstance() to create the object, and newInstance() returns An Object:

Class<?> c1 = Class.forName("com.chb.reflectTest.Test");Object o1 = c1.newInstance();
Copy after login
Copy after login

3.4. Obtaining data It is divided into all attributes and specified attributes

3.4.1. Obtaining all attributes

Get the modifications

  • First get the modification object through getModifiers() of the attribute,
    • Then through java.long. reflect.Modifier's toString() prints classes and attribute modifications (public, static, final, etc.).

    • Get attributes
  • Get all attributes: Return a Fielded array* through getDeclaedFields() of the Class object *.
    • Get the type of attribute:
      • 通过属性对象(Field对象)的getType()

    Class<?> cString = Class.forName("java.lang.String");
            //获取累的修饰和名称
            System.out.print(Modifier.toString(cString.getModifiers())+" class " + cString.getSimpleName()+"{\n");
            //获取所有属性
            Field[] fields = cString.getDeclaredFields();
            for (Field field : fields) {
                System.out.print("\t");
                System.out.print(
                        Modifier.toString(field.getModifiers())+" "//属性的修饰
                      + field.getType().getSimpleName()+" "
                      + field.getName()+"\n");           
            }
            System.out.println("}");
    Copy after login
    Copy after login

    3.4.2 获取指定属性

    创建测试对象:
    注意: 我在Use类中定义了两个属性, 一个public ,一个private ,是为了下一个测试反射可以打破封装性

    package com.chb.reflectTest;public class User {    
    private String name;    
    public  String nickName;    
    public User() {}    
    public User(String name, String nickName) {        
    this.name = name;        
    this.nickName = nickName;
        }
        setter getter...
    
    }
    Copy after login
    Copy after login

    传统属性的获取和通过反射获取对比:

    package com.chb.reflectTest;import java.lang.reflect.Field;public class Test1 {
        public static void main(String[] args) throws Exception {
            //传统获取属性的值
            //1、通过getter,setter
            User user1 = new User();
            user1.setName("lisi");
            System.out.println(user1.getName());
            //2、直接调用属性
            User user2 = new User();
            user2.nickName = "癞皮狗";
            System.out.println(user2.nickName);
            //=========================================
            //通过反射来设置,获取属性。
            Class<User> c1 = (Class<User>) Class.forName("com.chb.reflectTest.User");
            User user = c1.newInstance();
            Field nickField = c1.getDeclaredField("nickName");
            nickField.set(user, "123");
            System.out.println(nickField.get(user));
    
            Field nameFiled = c1.getDeclaredField("name");
            //Exception in thread "main" java.lang.IllegalAccessException: 
            Class com.chb.reflectTest.Test1 can not access a member of class com.chb.reflectTest.User with modifiers "private"
            nameFiled.setAccessible(true);
            nameFiled.set(user, "oup");
            System.out.println(nameFiled.get(user));
    
        }
    }
    Copy after login
    Copy after login

    通过反射来设置属性的值, 区别属性的修饰范围, 私有的不可以直接设置
    会出现访问错误, 也就是java的安全访问机制,报错:

    Exception in thread "main" java.lang.IllegalAccessException: Class com.chb.reflectTest.Test1 can not access a member of class com.chb.reflectTest.
    User with modifiers "private"
    Copy after login
    Copy after login

    我们通过一个方法·来打破java的封装性:

    nameFiled.setAccessible(true);
    Copy after login
    Copy after login

     以上就是java之反射基础的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

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

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

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.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

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

See all articles