发现Java基础还是不牢固,有必要复习以下:
-
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<?>...);
-
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(对象);
-
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);