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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李志群 中级黑马   /  2012-11-28 15:51  /  1307 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 李志群 于 2012-11-28 16:48 编辑

package cn.itcast.day1;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTest {
/**
  * @param args
  * @throws Exception
  */
public static void main(String[] args) throws Exception {
  
  
  String str = "abc";
  Class clas1  = str.getClass();
  Class clas2 = String.class;
  Class clas3 = Class.forName("java.lang.String");
  System.out.println(clas1==clas2);
  System.out.println(clas1==clas3);
  
  System.out.println(clas1.isPrimitive());
  System.out.println(int.class.isPrimitive());
  System.out.println(int.class==Integer.class);
  System.out.println(int.class==Integer.TYPE);
  System.out.println(int[].class.isPrimitive());
  System.out.println(int[].class.isArray());
  
  
  //new String(new StringBuffer("abs"));
  Constructor constructor = String.class.getConstructor(StringBuffer.class);
  String str2 =(String)constructor.newInstance(new StringBuffer("abc"));
  System.out.println(str2.charAt(2));
  
  ReflectPoint  pt1 = new ReflectPoint (3,5);
  Field filed = pt1.getClass().getField("y");
  //filed  Y的值是多少?是5就是错的。filed Y 不是对象身上的变量,而是类上的,要用它去取某个对象上对应的值
  System.out.println(filed.get(pt1));
  Field filed1 = pt1.getClass().getDeclaredField("x");
  filed1.setAccessible(true);
  System.out.println(filed1.get(pt1));
  
  
  changeStringValue(pt1);
  System.out.println(pt1);
  
  Method methodCharAt = String.class.getMethod(str,int.class);
  
  System.out.println(methodCharAt.invoke(str, 1));
  System.out.println(methodCharAt.invoke(str,new Object[]{2}));
//  Method methodCharAt = String.class.getMethod("CharAt",int.class);
//  
//  
//  System.out.println(methodCharAt.invoke(str,1));//这句输出怎么就出异常了 0 0!!!
}
public static void changeStringValue(Object obj) throws Exception{
  Field[]  fields = obj.getClass().getFields();
  for(Field field : fields){
   
   if(field.getType() == String.class){
    String oldValue =(String)field.get(obj);
    String newValue = oldValue.replace("b","a");
    field.set(obj, newValue);
   
   }
  }
}

}
打印的结果是:
true
true
false
true
false
true
false
true
c
5
3
ReflectPoint [str1=aall, str2=aasketaall, str3=itcast]
Exception in thread "main" java.lang.NoSuchMethodException: java.lang.String.abc(int)
at java.lang.Class.getMethod(Class.java:1622)
at cn.itcast.day1.ReflectTest.main(ReflectTest.java:48)
怎么会报异常呢?我照着打的 思路也对啊

评分

参与人数 1技术分 +1 收起 理由
刘芮铭 + 1 赞一个!

查看全部评分

0 个回复

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