国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java學習之反射機制及應用場景介紹

2019-11-26 13:32:46
字體:
來源:轉載
供稿:網友

前言:

最近公司正在進行業務組件化進程,其中的路由實現用到了Java的反射機制,既然用到了就想著好好學習總結一下,其實無論是之前的EventBus 2.x版本還是Retrofit、早期的View注解框架都或多或少的用到Java的反射機制。

什么是Java反射機制?

JAVA反射機制是在運行狀態中,對于任意一個類,都能夠知道這個類的所有屬性和方法;對于任意一個對象,都能夠調用它的任意一個方法;這種動態獲取的以及動態調用對象的方法的功能稱為Java的反射機制。

反射機制提供了哪些功能?

  • 在運行時判定任意一個對象所屬的類
  • 在運行時構造任意一個類的對象;
  • 在運行時判定任意一個類所具有的成員變量和方法;
  • 在運行時調用任意一個對象的方法;
  • 生成動態代理;

Java反射機制類:

java.lang.Class; //類        java.lang.reflect.Constructor;//構造方法 java.lang.reflect.Field; //類的成員變量    java.lang.reflect.Method;//類的方法java.lang.reflect.Modifier;//訪問權限

Java反射機制實現:
1.)class對象的獲取

//第一種方式 通過對象getClass方法Person person = new Person();Class<?> class1 = person.getClass();//第二種方式 通過類的class屬性class1 = Person.class;try {  //第三種方式 通過Class類的靜態方法――forName()來實現  class1 = Class.forName("com.whoislcj.reflectdemo.Person");} catch (ClassNotFoundException e) {  e.printStackTrace();}

2.)獲取class對象的摘要信息

boolean isPrimitive = class1.isPrimitive();//判斷是否是基礎類型boolean isArray = class1.isArray();//判斷是否是集合類boolean isAnnotation = class1.isAnnotation();//判斷是否是注解類boolean isInterface = class1.isInterface();//判斷是否是接口類boolean isEnum = class1.isEnum();//判斷是否是枚舉類boolean isAnonymousClass = class1.isAnonymousClass();//判斷是否是匿名內部類boolean isAnnotationPresent = class1.isAnnotationPresent(Deprecated.class);//判斷是否被某個注解類修飾String className = class1.getName();//獲取class名字 包含包名路徑Package aPackage = class1.getPackage();//獲取class的包信息String simpleName = class1.getSimpleName();//獲取class類名int modifiers = class1.getModifiers();//獲取class訪問權限Class<?>[] declaredClasses = class1.getDeclaredClasses();//內部類Class<?> declaringClass = class1.getDeclaringClass();//外部類

3.)獲取class對象的屬性、方法、構造函數等

Field[] allFields = class1.getDeclaredFields();//獲取class對象的所有屬性Field[] publicFields = class1.getFields();//獲取class對象的public屬性try {  Field ageField = class1.getDeclaredField("age");//獲取class指定屬性  Field desField = class1.getField("des");//獲取class指定的public屬性} catch (NoSuchFieldException e) {  e.printStackTrace();}Method[] methods = class1.getDeclaredMethods();//獲取class對象的所有聲明方法Method[] allMethods = class1.getMethods();//獲取class對象的所有方法 包括父類的方法Class parentClass = class1.getSuperclass();//獲取class對象的父類Class<?>[] interfaceClasses = class1.getInterfaces();//獲取class對象的所有接口Constructor<?>[] allConstructors = class1.getDeclaredConstructors();//獲取class對象的所有聲明構造函數Constructor<?>[] publicConstructors = class1.getConstructors();//獲取class對象public構造函數try {  Constructor<?> constructor = class1.getDeclaredConstructor(new Class[]{String.class});//獲取指定聲明構造函數  Constructor publicConstructor = class1.getConstructor(new Class[]{});//獲取指定聲明的public構造函數} catch (NoSuchMethodException e) {  e.printStackTrace();}Annotation[] annotations = class1.getAnnotations();//獲取class對象的所有注解Annotation annotation = class1.getAnnotation(Deprecated.class);//獲取class對象指定注解Type genericSuperclass = class1.getGenericSuperclass();//獲取class對象的直接超類的 TypeType[] interfaceTypes = class1.getGenericInterfaces();//獲取class對象的所有接口的type集合

4.)class對象動態生成

//第一種方式 Class對象調用newInstance()方法生成Object obj = class1.newInstance();//第二種方式 對象獲得對應的Constructor對象,再通過該Constructor對象的newInstance()方法生成Constructor<?> constructor = class1.getDeclaredConstructor(new Class[]{String.class});//獲取指定聲明構造函數obj = constructor.newInstance(new Object[]{"lcj"});

5.)動態調用函數

try {  // 生成新的對象:用newInstance()方法  Object obj = class1.newInstance();  //判斷該對象是否是Person的子類  boolean isInstanceOf = obj instanceof Person;  //首先需要獲得與該方法對應的Method對象  Method method = class1.getDeclaredMethod("setAge", new Class[]{int.class});  //調用指定的函數并傳遞參數  method.invoke(obj, 28);  method = class1.getDeclaredMethod("getAge");  Object result = method.invoke(obj, new Class[]{});} catch (InstantiationException e) {  e.printStackTrace();} catch (IllegalAccessException e) {  e.printStackTrace();} catch (NoSuchMethodException e) {  e.printStackTrace();} catch (InvocationTargetException e) {  e.printStackTrace();}

6.)通過反射機制獲取泛型類型

例如下面這種結構

//People類public class People<T> {}//Person類繼承People類public class Person<T> extends People<String> implements PersonInterface<Integer> {}//PersonInterface接口public interface PersonInterface<T> {}

獲取泛型類型

Person<String> person = new Person<>();//第一種方式 通過對象getClass方法Class<?> class1 = person.getClass();Type genericSuperclass = class1.getGenericSuperclass();//獲取class對象的直接超類的 TypeType[] interfaceTypes = class1.getGenericInterfaces();//獲取class對象的所有接口的Type集合getComponentType(genericSuperclass);getComponentType(interfaceTypes[0]);

getComponentType具體實現

private Class<?> getComponentType(Type type) {Class<?> componentType = null;if (type instanceof ParameterizedType) {  //getActualTypeArguments()返回表示此類型實際類型參數的 Type 對象的數組。  Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();  if (actualTypeArguments != null && actualTypeArguments.length > 0) {  componentType = (Class<?>) actualTypeArguments[0];  }} else if (type instanceof GenericArrayType) {  // 表示一種元素類型是參數化類型或者類型變量的數組類型  componentType = (Class<?>) ((GenericArrayType) type).getGenericComponentType();} else {  componentType = (Class<?>) type;}return componentType;}

6.)通過反射機制獲取注解信息

這里重點以獲取Method的注解信息為例

try {  //首先需要獲得與該方法對應的Method對象  Method method = class1.getDeclaredMethod("jumpToGoodsDetail", new Class[]{String.class, String.class});  Annotation[] annotations1 = method.getAnnotations();//獲取所有的方法注解信息  Annotation annotation1 = method.getAnnotation(RouterUri.class);//獲取指定的注解信息  TypeVariable[] typeVariables1 = method.getTypeParameters();  Annotation[][] parameterAnnotationsArray = method.getParameterAnnotations();//拿到所有參數注解信息  Class<?>[] parameterTypes = method.getParameterTypes();//獲取所有參數class類型  Type[] genericParameterTypes = method.getGenericParameterTypes();//獲取所有參數的type類型  Class<?> returnType = method.getReturnType();//獲取方法的返回類型  int modifiers = method.getModifiers();//獲取方法的訪問權限} catch (NoSuchMethodException e) {  e.printStackTrace();}

反射機制的應用場景:

  • 逆向代碼 ,例如反編譯
  • 與注解相結合的框架 例如Retrofit
  • 單純的反射機制應用框架 例如EventBus 2.x
  • 動態生成類框架 例如Gson

反射機制的優缺點:

 優點:運行期類型的判斷,動態類加載,動態代理使用反射。

 缺點: 性能是一個問題,反射相當于一系列解釋操作,通知jvm要做的事情,性能比直接的java代碼要慢很多。

總結:

Java的反射機制在平時的業務開發過程中很少使用到,但是在一些基礎框架的搭建上應用非常廣泛,今天簡單的總結學習了一下,還有很多未知的知識等以后用到再做補充。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 麻江县| 长泰县| 靖江市| 克东县| 肥东县| 太原市| 民乐县| 唐海县| 博爱县| 东莞市| 贡觉县| 三台县| 万年县| 曲阜市| 永福县| 南阳市| 大石桥市| 额尔古纳市| 周至县| 乐平市| 广灵县| 桂阳县| 湟中县| 藁城市| 苏州市| 巫溪县| 华蓥市| 永川市| 华坪县| 中山市| 夏邑县| 游戏| 台东市| 大竹县| 木里| 诸暨市| 上杭县| 温州市| 永昌县| 康马县| 洛隆县|