原文:http://blognojava.iteye.com/blog/799068
由于有了神奇的Class的,基本反射也就是利用这个资源搞一搞,但是功能却很吓人....很多不好理解,很突然的东西
package com.itcast.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class Demo02 {
public static void main(String[] args) throws Exception{
//理解反射的概念,利用Class得到类的成分,对应的是Field Method Constuctor Package 等
//得到一个类的所有构造方法
Constructor[] constructors=Class.forName("java.lang.String").getConstructors();
//得到一个类的指定构造方法
Constructor construtor=Class.forName("java.lang.String").getConstructor(StringBuffer.class);
/*运行时异常-->>Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
construtor.newInstance("abc");
*/
String str1=(String)construtor.newInstance(new StringBuffer("itcast"));
System.out.println(str1.charAt(2));
//在Class里面搞了一个便利的方法,直接给你构造方法,但无参的
String str2=new String();
String str3=(String)Class.forName("java.lang.String").newInstance();
String str4=(String)str2.getClass().newInstance();
System.out.println(str2==null);
System.out.println(str2==str3);
System.out.println(str2==str4);
System.out.println(str3==str4);
//成员变量反射demo
ReflectPoint rP1=new ReflectPoint(3,5);
Field field1=rP1.getClass().getField("y");
//field值是多少?结果是:public int com.itcast.test.ReflectPoint.y
System.out.println(field1);
//用对象上的名字去取值 结果:5
System.out.println(field1.get(rP1));
//同理取x
//Field field2=rP1.getClass().getField("x");
//报异常Exception in thread "main" java.lang.NoSuchFieldException: x
//System.out.println(field2);
//用另外的方式取值
Field field3=rP1.getClass().getDeclaredField("x");
System.out.println(field3);
/*取不到Exception in thread "main" java.lang.IllegalAccessException:
Class com.itcast.test.Demo02 can not access a member o
System.out.println(field3.get(rP1));*/
//居然提供暴力方法
field3.setAccessible(true);
System.out.println(field3.get(rP1));
}
}
package com.itcast.test;
public class ReflectPoint {
private int x;
public int y;
public ReflectPoint(int x, int y) {
this.x = x;
this.y = y;
}
}
一个反射小练习:把所有FieldValue中属性带有i的字母改成Y
package com.itcast.test;
public class FieldString {
public String name="zhoujielun";
public String address="*";
public String job="singer";
public int age=20;
@Override
public String toString() {
// TODO Auto-generated method stub
return "name:"+name+"address:"+address+"job:"+job+"age:"+age;
}
}
package com.itcast.test;
import java.lang.reflect.Field;
public class test01 {
public static void main(String[] args) throws Exception{
FieldString value1=new FieldString();
Field[] fields=value1.getClass().getFields();
for(Field field:fields){
//使用field.get()方式跟String类型做比较有问题,它返回时Object
if(field.getType()==String.class){
String oldValue=(String)field.get(value1);
System.out.println(oldValue);
String newValue=oldValue.replace('i', 'Y');
field.set(value1, newValue);
}
}
System.out.println(value1);
}
}