Java反射技术概述
生活随笔
收集整理的這篇文章主要介紹了
Java反射技术概述
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是Java反射
就是正在運行,動態獲取這個類的所有信息。
反射機制的作用
? 1,反編譯:.class-->.java
???2.通過反射機制訪問java對象的屬性,方法,構造方法等;
反射機制的應用場景
Jdbc 加載驅動-----
Spring ioc
框架
package com.learn.entity;/*** @classDesc: 功能描述:(用戶實體類)* */ public class UserEntity {private String userId;private String userName;public UserEntity(){System.out.println("使用反射技術 ,執行無參數構造 函數");}public UserEntity(String userId) {System.out.println("使用反射技術 執行 有參構造函數 userId:"+userId);}public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}} package com.learn.classFrorm;import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException;import com.learn.entity.UserEntity;public class ClassFrom {public static void main(String[] args)throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException,SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {// // 1.除了new創建對象,還可以使用反射機制創建對象。// // 2.forName 必須傳入 class 類的完整路徑。// Class<?> forName = Class.forName("com.learn.entity.UserEntity");// // 3.newInstance使用無參構造函數 創建對象 new// Object newInstance = forName.newInstance();// UserEntity user = (UserEntity) newInstance;// System.out.println("user:" + user);// user.setUserId("123");// System.out.println(user.getUserId());// // 使用反射技術創建對象和new 那個效率高? new 效率高。 hibernate// Class<?> forName = Class.forName("com.learn.entity.UserEntity");// Constructor<?> constructor = forName.getConstructor(String.class);// Object newInstance = constructor.newInstance("11");// UserEntity user=(UserEntity) newInstance;Class<?> forName = Class.forName("com.learn.entity.UserEntity");// 獲取所有該類的所有方法 // Method[] declaredMethods = forName.getMethods(); // for (Method method : declaredMethods) { // System.out.println(method.getName() + "-----" + // method.getReturnType()); // }// 拿到所有成員屬性 // Field[] declaredFields = forName.getDeclaredFields(); // for (Field field : declaredFields) { // System.out.println(field.getName()); // }// 為什么繼承里面沒有//可以使用Java反射技術 可以訪問到私有屬性。Field declaredField = forName.getDeclaredField("userId");Object obj = forName.newInstance();// 允許訪問私有成員屬性declaredField.setAccessible(true);declaredField.set(obj, "123");UserEntity user=(UserEntity) obj;System.out.println(user.getUserId());}}?
反射創建api
| 方法名稱 | 作用 |
| getDeclaredMethods [] | 獲取該類的所有方法 |
| getReturnType() | 獲取該類的返回值 |
| getParameterTypes() | 獲取傳入參數 |
| getDeclaredFields() | 獲取該類的所有字段 |
| setAccessible | 允許訪問私有成員 |
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的Java反射技术概述的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 组装json
- 下一篇: SpringIOC概述