- import java.lang.reflect.*;
- class ReflectDemo1
- {
- public static void main(String args[])throws Exception
- {
- ReflectPoint pt1=new ReflectPoint(3,5);
- Field []fields=pt1.getClass().getFields();
- for(Field f : fields)
- {
- if(f.getType()==String.class)
- {
- String s=(String)f.get(pt1);
- String s1=s.replace("b","a");
- f.set(pt1,s1);
-
- }
- }
- System.out.println(pt1.toString());
- }
- }
- class ReflectPoint
- {
- private int x;
- public int y;
- public String str1="ball";
- public String str2="basketball";
- public String str3="itcast";
- public ReflectPoint(int x,int y)
- {
- super();
- this.x=x;
- this.y=y;
- }
- public String toString()
- {
- return str1+":"+str2+":"+str3;
- }
- }
复制代码 请问:在for循环中会遍历所有的fields数组中的内容,因为x和y是int型的,所以if(f.getType()==String.class)
这一句也会判断if(int.class==String.class),请问如果我们单独搞段代码System.out.println(int.class==String.class)显示判断结果,会报错“不可比较的类型"。为什么这里遍历到的int.class就可以和String.class比较呢?? |