本帖最后由 gerenvip 于 2013-4-28 09:08 编辑
- <div class="blockcode"><blockquote>import java.lang.reflect.*;
- 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;
- }
- }
- class Test1
- {
- private static void changeStringValue(Object obj) throws Exception
- {
- Field[] fields = obj.getClass().getFields();
- for(Field field : fields)
- {
- //if(field.getType().equals(String.class)){
- if(field.getType() == (String.class))
- {
- String oldValue = (String)field.get(obj);
- String newValue = oldValue.replace('b','a');
- field.set(obj, newValue);
- System.out.println(field.getName());
-
- System.out.println("比较1:"+(field.getType() == (String.class)));
- System.out.println("比较2:"+(field.getType() == (int.class)));
- System.out.println("比较3:"+(String.class == (String.class)));
- //System.out.println("比较4-1:"+(int.class == (String.class)));//报错
- System.out.println("比较4-2:"+((Object)int.class == (String.class)));
- System.out.println("比较5:"+(int.class.equals(String.class)));
- }
- }
- }
- public static void main(String[] args)throws Exception
- {
-
- ReflectPoint pt1 = new ReflectPoint(3,5);
- changeStringValue(pt1);
- System.out.println(pt1);
- }
- }
复制代码 输出打印结果为:
str1
比较1:true
比较2:false
比较3:true
比较5:false
str2
比较1:true
比较2:false
比较3:true
比较5:false
str3
比较1:true
比较2:false
比较3:true
比较5:false
aall:aasketaall:itcast
请大家看看 “比较2”和“比较4-1”,经过if选择,filed的类型是String类型是
getType的返回类型是Class,为什么一个能执行,一个不能
另外比较4-1和4-2的区别是什么?
|