天天看点

使用Java反射机制实现访问类中的私有变量或者方法

package com.test;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

public class ReflectDemo {

    public static void main(String[] args) throws Exception {

        PrivateTest t = new PrivateTest();

        Field field = Class.forName("com.test.PrivateTest").getDeclaredField(

                "str");

        // 不让Java语言检查访问修饰符

        field.setAccessible(true);

        field. set(t, "world");

        t.getStr();

        Method method2 = Class.forName("com.test.PrivateTest")

                .getDeclaredMethod("method", new Class[] {});

        method2.setAccessible(true);

        method2. invoke(t, new Object[] {});

    }

}

class PrivateTest {

    private String str = "hello";

    public void getStr() {

        System.out

                .println("I'm str,I'm a private field,my old value is hello,now I am --->"

                        + str);

    }

    private void method() {

        System.out.println("I'm in a private method!");

    }

}

--------------结果---------------------

I'm str,I'm a private field,my old value is hello,now I am --->world

I'm in a private method!