Java反射的方法簡單解釋

發現Java基礎還是不牢固,有必要複習以下:

  1. Class方法

    Class mClass = User.class;
    //獲取所有public變量,包括父類的
    Field[] fields = mClass.getFields();
    //獲取當前類聲明的所有變量,不包括父類的
    Filed[] fileds = mClass.getDeclaredFileds();
    //返回指定的變量;需要捕獲異常NoSuchMethodException
    Filed filed = mClass.getDeclaredFiled("變量名");
    //獲取所有public方法,包括父類的
    Method[] mMethods = mClass.getMethods();
    //獲取所有當前類的方法,不包括父類的
    Method[] mMethods = mClass.getDeclaredMethods();
    //返回指定的方法對象,第一個參數方法名字符串,第二個爲該方法所需參數的類型;
    //需要捕獲異常NoSuchMethodException
    Method method = mClass.getDeclaredMethod("方法名", Class<?>...);
    
  2. Filed方法

    //返回訪問權限修飾符,如public、private、private static、private static final
    String modifier = Modifier.toString(field.getModifier());
    //返回字段名字,如mAge、mName
    String name = filed.getName();
    //返回字段類型
    Class<?> type = field.getType();
    filed.setAccessible(true);
    //將‘對象’的成員變量‘field’的值改爲‘值1’
    field.set(對象,1);
    //獲取‘對象’的成員變量‘field’的值
    field.get(對象);
    
  3. Method方法

    //返回訪問權限修飾符,如public、private、private static、private static final
    String modifier = Modifier.toString(method.getModifier());
    //返回方法返回值類型
    Class<?> returnType = method.getReturnType();
    //返回方法名
    String name = method.getName();
    //返回方法參數
    Parameter[] parameters = method.getParameters();
    //返回參數名
    parameter.getName();
    //返回參數類型
    parameter.getType();
    //返回方法拋出的異常
    Class<?>[] exceptionTypes = method.getExceptionTypes();
    //獲取私有方法的訪問權,否則‘invoke’私有方法會報IllegalAccessException
    method.setAccessible(true);
    //‘對象’要執行‘method’方法,該方法要傳兩個參數分別是‘參數1’、‘參數2’
    method.invoke(對象, 參數1, 參數2);
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章