Table of Contents
1. What is a class
2. Dynamic loading of class classes
3. Obtain method information
五、获取构造函数的信息
六、方法反射的操作
Home Java javaTutorial Summary of knowledge about Java reflection mechanism that needs to be mastered

Summary of knowledge about Java reflection mechanism that needs to be mastered

Apr 09, 2017 am 10:35 AM

反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。【翻译于 官方文档】
Copy after login


This article will introduce the knowledge of reflection from the following aspects: reflection of

class using

method

Reflection of constructor

Reflection of member variables

1. What is a class

In the object-oriented world, everything is an object. Classes are objects, and classes are instance objects of the java.lang.Class class. In addition, the class class can only be new by the Java virtual machine. Any class is an instance object of the Class class. This instance object has three expression methods:

public class User{
}

public class ClassTest{
User u=new User();
//Method 1 :
Class c1=User.class;
//Method 2:
Class c2=u.getClass();
//Method 3:
Class c3=Class.forName(" com.forezp.User");

//You can create an instance object of the class through the type of the class
User user=(User)c1.newInstance();
}

2. Dynamic loading of class classes

Class.forName (full name of the class); This method not only represents the type of the class, but also represents the dynamically loaded class. Classes loaded at compile time are statically loaded, and classes loaded at runtime are dynamically loaded.

3. Obtain method information

Basic data types and void keywords are instances of the Class class; the name of the class can be obtained through getame();getSimpleName() .

Class c1=String.class;
Class c2=int.class;
Class c3=void.class;
System.out.println(c1.getName());
System.out.println(c2.getSimpleName());
Get all methods of the class and print them out:

public static void printClassInfo(Object object){
Class c=object .getClass();
System.out.println("Name of class: "+c.getName());

/**
* A member method is a method object
* getMethod() gets all the public methods, including those inherited from the parent class
* getDeclaredMethods() gets all the methods of the class, including private, but not inherited Methods.
         */
Method[] methods= c.getMethods();//Get methods
//Get all methods, including private,c.getDeclaredMethods();

for(int i=0;i                                                                                                                                                   use using using using                 out out through off ’s off ’s ‐ ‐ ‐ ‐‐ ‐ ‐                                                                                                  :
System.out.print(methods[i].getName()+"(");

Class[] parameterTypes=methods[i].getParameterTypes();
for(Class class1:parameterTypes){
              System.out.print(class1.getName()+",");
          }
            System.out.println(")");
    }
}
public class ReflectTest {

public static void main(String[] args){
String s="ss";
ClassUtil.printClassInfo(s);
}
}
Run:


类的名称:java.lang.String

booleanequals(java.lang.Object,)

java.lang.StringtoString()

inthashCode()

…
Copy after login

4. Obtain the member variable information
You can also obtain the member variable information of the class

public static void printFiledInfo(Object o){


Class c=o.getClass();
/**
* getFileds() gets public
* getDeclaredFields() gets all
*/
Field[] fileds=c.getDeclaredFields();

for (FIELD F: FILEDS) {
// The type of member variables
Class Filedtype = f.gettype ();
System.Println (Filedtype.getName ()+"" "" +f.getName());
}
## }
public static void main(String[] args){
              String s="ss";
                                                                                                    ’ s ’ s =" s s t t                ’       ‐ ‐ ‐ ‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ printClassInfo(s);
ClassUtil.printFiledInfo(s);
}
Run:


[C value

int hash

long serialVersionUID

[Ljava.io.ObjectStreamField; serialPersistentFields

java.util.Comparator CASE_INSENSITIVE_ORDER

int HASHING_SEED

int hash32
Copy after login

五、获取构造函数的信息

public static void printConstructInfo(Object o){
       Class c=o.getClass();

       Constructor[] constructors=c.getDeclaredConstructors();
       for (Constructor con:constructors){
           System.out.print(con.getName()+”(“);

           Class[] typeParas=con.getParameterTypes();
           for (Class class1:typeParas){
               System.out.print(class1.getName()+” ,”);
           }
           System.out.println(“)”);
       }
   }
public static void main(String[] args){
               String s="ss";
               //ClassUtil.printClassInfo(s);
               //ClassUtil.printFiledInfo(s);
               ClassUtil.printConstructInfo(s);
       }
运行:

java.lang.String([B ,)

java.lang.String([B ,int ,int ,)

java.lang.String([B ,java.nio.charset.Charset ,)

java.lang.String([B ,java.lang.String ,)

java.lang.String([B ,int ,int ,java.nio.charset.Charset ,)

java.lang.String(int ,int ,[C ,)

java.lang.String([C ,boolean ,)

java.lang.String(java.lang.StringBuilder ,)

java.lang.String(java.lang.StringBuffer ,)

...
Copy after login

六、方法反射的操作

获取一个方法:需要获取方法的名称和方法的参数才能决定一个方法。

方法的反射操作:

method.invoke(对象,参数列表);
举个例子:

class A{

   public void add(int a,int b){
       System.out.print(a+b);
   }

   public void toUpper(String a){
       System.out.print(a.toUpperCase());
   }
}
public static void main(String[] args) {
       A a=new A();
       Class c=a.getClass();
       try {
           Method method=c.getMethod("add",new Class[]{int.class,int.class});
           //也可以 Method method=c.getMethod("add",int.class,int.class);
           //方法的反射操作
           method.invoke(a,10,10);
       }catch (Exception e){
           e.printStackTrace();
       }
   }
运行:

20
Copy after login


本篇文章已经讲解了java反射的基本用法, 它可以在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。

The above is the detailed content of Summary of knowledge about Java reflection mechanism that needs to be mastered. 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

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 are the alternatives to Java's reflection mechanism? What are the alternatives to Java's reflection mechanism? Apr 15, 2024 pm 02:18 PM

Alternatives to the Java reflection mechanism include: 1. Annotation processing: Use annotations to add metadata and generate code at compile time to process the information. 2. Metaprogramming: Generate and modify code at runtime, and can dynamically create classes and obtain information. 3. Proxy: Create a new class with the same interface as an existing class, which can enhance or modify its behavior at runtime.

How does the Java reflection mechanism modify the behavior of a class? How does the Java reflection mechanism modify the behavior of a class? May 03, 2024 pm 06:15 PM

The Java reflection mechanism allows programs to dynamically modify the behavior of classes without modifying the source code. By operating the Class object, you can create instances through newInstance(), modify private field values, call private methods, etc. Reflection should be used with caution, however, as it can cause unexpected behavior and security issues, and has a performance overhead.

How is the NoSuchFieldException exception in Java generated? How is the NoSuchFieldException exception in Java generated? Jun 25, 2023 pm 04:30 PM

Java is one of the most widely used programming languages ​​in the world, and exception handling is a very important part of the Java programming process. This article will introduce the NoSuchFieldException exception in Java, how it is generated and how to deal with it. 1. Definition of NoSuchFieldException NoSuchFieldException is a Checked exception in Java, which means it is thrown when the specified field is not found.

Application of Java reflection mechanism in Spring framework? Application of Java reflection mechanism in Spring framework? Apr 15, 2024 pm 02:03 PM

Java reflection mechanism is widely used in Spring framework for the following aspects: Dependency injection: instantiating beans and injecting dependencies through reflection. Type conversion: Convert request parameters to method parameter types. Persistence framework integration: mapping entity classes and database tables. AspectJ support: intercepting method calls and enhancing code behavior. Dynamic Proxy: Create proxy objects to enhance the behavior of the original object.

Application of reflection mechanism in Java concurrency? Application of reflection mechanism in Java concurrency? Apr 15, 2024 pm 09:03 PM

Answer: The reflection mechanism allows Java programs to inspect and modify classes and objects at runtime through the reflection API, which can be used to implement flexible concurrency mechanisms in Java concurrency. Application: Dynamically create threads. Dynamically change thread priority. Inject dependencies.

Application of Java reflection mechanism in cloud computing? Application of Java reflection mechanism in cloud computing? Apr 16, 2024 am 09:18 AM

Java reflection is widely used in cloud computing, including: dynamic service discovery (obtaining service classes from the service registry and calling methods), automatic expansion and contraction (monitoring system indicators and adjusting the number of service instances), dynamic configuration loading, and code generation and custom exception handling. Through reflection, programs can easily adapt to the dynamic and distributed characteristics of cloud computing environments and implement automated tasks such as automated deployment.

Reflection mechanism in PHP Reflection mechanism in PHP Aug 31, 2023 pm 01:57 PM

Reflection is usually defined as the ability of a program to examine itself and modify its logic while executing. In less technical terms, reflection is asking an object to tell you its properties and methods, and changing those members (even private members). In this course, we'll take a closer look at how to accomplish this, and when it might be useful. A little history At the beginning of the programming era, assembly language emerged. Programs written in assembly language reside in physical registers inside the computer. Its composition, methods and values ​​can be checked at any time by reading the registers. What's more, you can change your program by simply modifying these registers while it's running. It requires some deep knowledge of the running program, but it is reflective in nature. As with any cool toy

PHP Advanced Features: Understand the Power of Reflection Mechanism PHP Advanced Features: Understand the Power of Reflection Mechanism Jun 01, 2024 pm 07:40 PM

PHP reflection is a powerful mechanism for obtaining runtime code structure information. It allows you to: 1. Check the structure of classes and methods; 2. Call private methods; 3. Create instances of new classes; 4. Modify class definitions; 5. Obtain method parameter information; 6. Modify attribute values; 7. Call private methods. Through reflection, you can enhance the scalability and flexibility of your code and develop more powerful PHP applications.

See all articles