日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java反射技术概述

發布時間:2024/4/13 java 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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反射技术概述的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。