import java.lang.reflect.Field; |
public class ReflectTest{ |
public static void main(String[] args){ |
String str1= "abc" ; |
Class cls1=str1.getClass(); |
Class cls2=String. class ; |
//Class cls3=Class.forName("java.lang.String"); |
System.out.println(cls1==cls2); |
// System.out.println(cls1==cls3); |
System.out.println(cls1.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()); |
try { |
//获取相对应的字段 |
ReflectPoint pt1= new ReflectPoint( 3 , 5 ); |
Field fieldY=pt1.getClass().getField( "y" ); |
System.out.println(fieldY.get(pt1)); |
Field fieldx=pt1.getClass().getDeclaredField( "x" ); |
fieldx.setAccessible( true ); |
System.out.println( "a" +fieldx.get(pt1)); |
changeStringValue(pt1); |
System.out.println(pt1); |
} catch (Exception e2) |
{ |
System.out.println(e2); |
} |
} |
private static void changeStringValue(Object obj) throws Exception { |
Field[] fields=obj.getClass().getFields(); |
for (Field field:fields){ |
//field.getType().equals(String.class); |
if (field.getType()==String. class ) |
{ |
//以后是取出相应的字段,然后用replace方法下替换字符 |
String oldValue=(String)field.get(obj); |
String newValue=oldValue.replace( 'b' , 'a' ); |
field.set(obj, newValue); |
} |
} |
|
} |
} |