Java學習之反射機制及應用情境

來源:互聯網
上載者:User

標籤:行業   android   傳遞參數   parameter   學習   trie   通過   狀態   補充   

前言:

      最近公司進行中業務組件化進程,其中的路由實現用到了Java的反射機制,既然用到了就想著好好學習總結一下,其實無論是之前的EventBus 2.x版本還是Retrofit、早期的View註解架構都或多或少的用到Java的反射機制。以下是自己使用反射的兩個地方,感興趣的同學可以看下:Android okHttp網路請求之Json解析,Android業務組件化之子模組SubModule的拆分以及它們之間的路由Router實現。

什麼是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的反射機制在平時的業務開發過程中很少使用到,但是在一些基礎架構的搭建上應用非常廣泛,今天簡單的總結學習了一下,還有很多未知的知識等以後用到再做補充。

Java學習之反射機制及應用情境

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.