search
HomeJavajavaTutorialSummary of knowledge about Java reflection mechanism that needs to be mastered

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


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()

…

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

五、获取构造函数的信息

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 ,)

...

六、方法反射的操作

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

方法的反射操作:

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


本篇文章已经讲解了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
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
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft