天天看点

Java反射访问私有成员

 field.setAccessible(true);

import java.lang.reflect.*; 

public class Main 

    class Test 

    { 

        private int id = 5; 

    } 

    public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InstantiationException 

        Field field = Test.class.getDeclaredField("id"); 

        field.setAccessible(true);//suppress Java language access checking 

        Main m = new Main(); 

        Test obj = m.new Test(); 

        int id = field.getInt(obj); 

        System.out.println(id); 

本文转自 dogegg250 51CTO博客,原文链接:http://blog.51cto.com/jianshusoft/652658,如需转载请自行联系原作者