Reflection basics of 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
2. The role of reflection
1. Decompilation: .class–>java
- ##2 , Access the properties, methods, constructors, etc. of objects through the reflection mechanism
- 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(); } }
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();
It is divided into all attributes and specified attributes
3.4.1. Obtaining all attributes
- Get the modifications
- Then through java.long. reflect.Modifier's toString() prints classes and attribute modifications (public, static, final, etc.).
- First get the modification object through getModifiers() of the attribute,
- Get all attributes: Return a Fielded array* through getDeclaedFields() of the Class object *.
- 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("}");
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 encapsulationpackage 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...
}
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)); } }
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"
We use a method to break the encapsulation of java:
nameFiled.setAccessible(true);
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
- 1. Decompilation: .class–>java
- ##2 , Access the properties, methods, constructors, etc. of objects through the reflection mechanism
- 3. Specific implementation of reflection
- 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(); } }
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();
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("}");
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... }
传统属性的获取和通过反射获取对比:
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)); } }
通过反射来设置属性的值, 区别属性的修饰范围, 私有的不可以直接设置
会出现访问错误, 也就是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"
我们通过一个方法·来打破java的封装性:
nameFiled.setAccessible(true);
以上就是java之反射基础的内容,更多相关内容请关注PHP中文网(www.php.cn)!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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

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

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.

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

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
