A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Mr_Unhappy 中级黑马   /  2014-9-14 16:06  /  547 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. package FieldDemo;

  2. import java.lang.reflect.Field;

  3. public class FieldTest {
  4.         public static void main(String[] args)
  5.                         throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
  6.                 Test test = new Test("li","wu");
  7.                 Field testX = test.getClass().getField("x");
  8.                 System.out.println(testX.get(test));
  9.                
  10.                 //暴力反射
  11.                 Field testY = Class.forName("FieldDemo.Test").getDeclaredField("y");
  12.                 //设置y为可见
  13.                 testY.setAccessible(true);
  14.                 System.out.println(testY.get(test));
  15.         }
  16. }
  17. class Test{
  18.         public String x;
  19.         private String y;
  20.         public Test(String x, String y) {
  21.                 super();
  22.                 this.x = x;
  23.                 this.y = y;
  24.         }
  25. }
复制代码




在此处,是通过new Test对象来得到Test类对应的Class对象,你有没有试过,用其他两种方式来得到Test类对应的Class对象?你猜猜,用其他两种方式会不会成立,结果会吓你一大跳的{:2_40:}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马