通过java反射访问和修改成员变量和成员方法

通过java的反射机制,可以在程序运行时访问已经装载到JVM中的java对象描述,实现访问、检测和修改描述java对象本身信息的功能。

  • 1.访问和修改成员变量

    public class TestField {
        public static void main(String[] args) {
            Example02 example = new Example02();
            Class exampleClass = example.getClass(); //获得Example02的class反射对象
            Field[] declaredFields = exampleClass.getDeclaredFields();//获取该类所有成员变量
            for (int i = 0; i < declaredFields.length; i++) {
                Field field = declaredFields[i];
                System.out.println("成员变量名称:"+field.getName());
                Class fieldType = field.getType();
                System.out.println("成员变量类型:"+fieldType);
                boolean flag=true;
                while (flag){
                    //如果成员变量的访问权限为private,则抛出异常,即不允许访问
                    try {
                        flag=false;
                        System.out.println("修改前的值:"+field.get(example)); //get()方法能获取各种类型成员变量的值
                        if (fieldType.equals(int.class)){ //判断成员变量类型是否是int型
                            System.out.println("利用setInt()方法修改成员变量的值");
                            field.setInt(example,150); //为int型成员变量赋值
                        } else if (fieldType.equals(float.class)){ //判断成员变量类型是否是float型
                            System.out.println("利用setFloat()方法修改成员变量的值");
                            field.setFloat(example,5.25f); //为float型成员变量赋值
                        }else if (fieldType.equals(boolean.class)){ //判断成员变量类型是否是boolean型
                            System.out.println("利用setBoolean()方法修改成员变量的值");
                            field.setBoolean(example,true); //为boolean型成员变量赋值
                        }else {
                            System.out.println("利用set()方法修改成员变量的值");
                            field.set(example,"Good"); //set()方法可以为各种类型成员变量赋值
                        }
                        System.out.println("成员变量修改后的值:"+field.get(example));
                    }catch (Exception e){
                        //e.printStackTrace();
                        System.out.println("在设置成员变量值时出现异常,可能是权限不允许,下面执行setAccessible方法");
                        field.setAccessible(true); //默认false不允许访问私有变量,现在设置为允许
                        flag=true;
                    }
                }
                System.out.println();
            }
    
        }
    }
    
    class Example02{
        int i=1;
        public float f=2.5f;
        protected boolean b=false;
        private String s="Hello";
    }
    
  • 2.访问和修改成员方法

    public class TestMethod {
        public static void main(String[] args) {
            Example03 example03 = new Example03();
            Class exampleClass = example03.getClass();  //获取class反射对象
            Method[] declaredMethods = exampleClass.getDeclaredMethods();
            for (int i = 0; i < declaredMethods.length; i++) {
                Method method=declaredMethods[i];
                System.out.println("成员方法的名称是:"+method.getName()); //获取成员方法的名称
                System.out.println("是否允许该方法带有可变数量的参数:"+method.isVarArgs()); //返回true表示允许
                System.out.println("方法入口参数类型依次为:");
                Class[] parameterTypes = method.getParameterTypes();
                for (int i1 = 0; i1 < parameterTypes.length; i1++) {
                    System.out.println(" "+parameterTypes[i1]);
                }
                System.out.println("方法返回值类型为:"+method.getReturnType());
                System.out.println("方法可能抛出的异常类型为:");
                Class[] exceptionTypes = method.getExceptionTypes();
                for (int i2 = 0; i2 < exceptionTypes.length; i2++) {
                    System.out.println(" "+exceptionTypes[i2]);
                }
                boolean flag=true;
                while (flag){
                    //如果成员变量的访问权限为private,则抛出异常,即不允许访问
                    try {
                        flag=false;
                        if ("staticMethod".equals(method.getName())){
                            method.invoke(example03);
                        }else if ("publicMethod".equals(method.getName())){
                            System.out.println("返回值为:"+method.invoke(example03, 155));
                        }else if ("protectedMethod".equals(method.getName())){
                            System.out.println("返回值为:"+method.invoke(example03, "10",8));
                        } else if ("privateMethod".equals(method.getName())){
                            Object[] parameters = {new String[]{"A", "B", "C"}};
                            System.out.println("返回值为:"+method.invoke(example03,parameters));
                        }
                    }catch (Exception e){
                        //e.printStackTrace();
                        System.out.println("在执行成员方法时出现异常,可能是权限不允许,下面执行setAccessible方法");
                        method.setAccessible(true); //默认false不允许访问私有方法,现在设置为允许
                        flag=true;
                    }
                }
                System.out.println();
    
            }
        }
    }
    
    class Example03{
        static void staticMethod(){
            System.out.println("执行了staticMethod方法");
        }
        public int publicMethod(int i){
            System.out.println("执行了publicMethod方法");
            return i*50;
        }
        protected int protectedMethod(String s,int i) throws NumberFormatException{
            System.out.println("执行了protectedMethod方法");
            return Integer.valueOf(s)+i;
        }
        private String privateMethod(String...strings){
            System.out.println("执行了privateMethod方法");
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < strings.length; i++) {
                stringBuffer.append(strings[i]);
            }
            return stringBuffer.toString();
        }
    }
    

你可能感兴趣的:(java,反射)