轉載:https://www.cnblogs.com/whoislcj/p/6038511.html
什么是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對象的直接超類的 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代碼要慢很多。