This document describes the analysis and introduction of Java reflection
1. What is reflection?
From Baidu Encyclopedia, we can know that Java reflection is in the running state. For any class, we can know all the properties and methods of this class; for any object, we can call any of its methods and properties; and can change its properties. And this is why Java is considered dynamic (or quasi-dynamic, why is it said to be quasi-dynamic, because the general definition of a dynamic language is that when the program is running, it allows the program structure or variable type to be changed. This language is called a dynamic language. From this point of view, Perl, Python, and Ruby are dynamic languages, and C++, Java, and C# are not dynamic languages.) A key property of languages.
2. What can reflection do?
We know that the reflection mechanism allows the program to obtain the internal information of any class with a known name at runtime, including its modifiers (modifiers), fields (properties), methods (methods), etc., and can be changed at runtime. fields content or calling methods. Then we can write code more flexibly, and the code can be assembled at runtime without the need for source code linking between components, reducing the coupling of the code; there is also the implementation of dynamic agents, etc.; but we need to pay attention to the improper use of reflection. It will be very costly!
3. The specific implementation of reflection
The following is a basic class Person
package com.ys.reflex; public class Person { //私有属性 private String name = "Tom"; //公有属性 public int age = 18; //构造方法 public Person() { } //私有方法 private void say(){ System.out.println("private say()..."); } //公有方法 public void work(){ System.out.println("public work()..."); } }
①. Get the Class 3 This way
//1、通过对象调用 getClass() 方法来获取,通常应用在:比如你传过来一个 Object // 类型的对象,而我不知道你具体是什么类,用这种方法 Person p1 = new Person(); Class c1 = p1.getClass(); //2、直接通过 类名.class 的方式得到,该方法最为安全可靠,程序性能更高 // 这说明任何一个类都有一个隐含的静态成员变量 class Class c2 = Person.class; //3、通过 Class 对象的 forName() 静态方法来获取,用的最多, // 但可能抛出 ClassNotFoundException 异常 Class c3 = Class.forName("com.ys.reflex.Person");
It should be noted that:A class will only have one Class instance in the JVM,That is, we will perform the above-obtained c1, c2, c3 equals comparison, found to be true
②,Get member variables, member methods, interfaces, super classes, constructors, etc. through the Class class
Check the API and you can see that Class has many methods:
GetName(): Get the complete name of the class.
GetFields(): Get the public type attributes of the class.
getDeclaredFields(): Get all attributes of the class. Including private declared and inherited classes
GetMethods(): Get the public type method of the class.
getDeclaredMethods(): Get all methods of the class. Including private declared and inherited classes
GetMethod(String name, Class[] parameterTypes): Get the specific method of the class, the name parameter specifies the name of the method, and the parameterTypes parameter specifies the parameter type of the method.
GetConstructors(): Get the public type constructor of the class.
getConstructor(Class[] parameterTypes): Get the specific constructor method of the class. The parameterTypes parameter specifies the parameter type of the constructor method.
newInstance(): Create an object of this class through the constructor method of the class without parameters.
We use an example to comprehensively demonstrate the above method:
//获得类完整的名字 String className = c2.getName(); System.out.println(className);//输出com.ys.reflex.Person //获得类的public类型的属性。 Field[] fields = c2.getFields(); for(Field field : fields){ System.out.println(field.getName());//age } //获得类的所有属性。包括私有的和继承类的 Field [] allFields = c2.getDeclaredFields(); for(Field field : allFields){ System.out.println(field.getName());//name age } //获得类的public类型的方法。这里包括 Object 类的一些方法 Method [] methods = c2.getMethods(); for(Method method : methods){ System.out.println(method.getName());//work waid equls toString hashCode等 } //获得类的所有方法。 Method [] allMethods = c2.getDeclaredMethods(); for(Method method : allMethods){ System.out.println(method.getName());//work say } //获得指定的属性 Field f1 = c2.getField("age"); System.out.println(f1); //获得指定的私有属性 Field f2 = c2.getDeclaredField("name"); //启用和禁用访问安全检查的开关,值为 true,则表示反射的对象在使用时应该取消 java 语言的访问检查;反之不取消 f2.setAccessible(true); System.out.println(f2); //创建这个类的一个对象 Object p2 = c2.newInstance(); //将 p2 对象的 f2 属性赋值为 Bob,f2 属性即为 私有属性 name f2.set(p2,"Bob"); //使用反射机制可以打破封装性,导致了java对象的属性不安全。 System.out.println(f2.get(p2)); //Bob //获取构造方法 Constructor [] constructors = c2.getConstructors(); for(Constructor constructor : constructors){ System.out.println(constructor.toString());//public com.ys.reflex.Person() }
4. Reflection summary
Flexible use of reflection can make our code more flexible, here is an example of JDBC native code registration Drivers, hibernate's entity classes, Spring's AOP, etc. all have reflection implementations. But everything has two sides. Reflection will also increase the performance and complexity of the system. Reasonable use is the truth!
The above is the detailed content of Introduction to analysis of Java reflection. For more information, please follow other related articles on the PHP Chinese website!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
