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

前言:

      最近公司正在進行業務組件化進程,其中的路由實現用到了Java的反射機制,既然用到了就想着好好學習總結一下,其實不管是以前的EventBus 2.x版本仍是Retrofit、早期的View註解框架都或多或少的用到Java的反射機制。如下是本身使用反射的兩個地方,感興趣的同窗能夠看下:Android okHttp網絡請求之Json解析Android業務組件化之子模塊SubModule的拆分以及它們之間的路由Router實現html

什麼是Java反射機制?

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

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

  • 在運行時斷定任意一個對象所屬的類數組

  • 在運行時構造任意一個類的對象;網絡

  • 在運行時斷定任意一個類所具備的成員變量和方法;框架

  • 在運行時調用任意一個對象的方法;jvm

  • 生成動態代理;函數

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對象的直接超類的 Type
Type[] 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對象的直接超類的 Type
Type[] 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的反射機制在平時的業務開發過程當中不多使用到,可是在一些基礎框架的搭建上應用很是普遍,今天簡單的總結學習了一下,還有不少未知的知識等之後用到再作補充。

相關文章
相關標籤/搜索