String str="abc";
Class cls1=str.getClass();
Class cls2=String.class;
Class cls3= Class.forName("java.lang.String");
System.out.println(cls1==cls2);
System.out.println(cls2==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());//基本类型
System.out.println(int[].class.isArray());//数组
输出结果:
true
true
false
true
false
true
false
true
构造函数的反射运用:
Constructor constroctor1 = String.class.getConstructor(StringBuffer.class);
String str2= (String)constroctor1.newInstance(new StringBuffer("abc"));
System.out.println(str2.charAt(2));
输出 c
通过反射取 变量
ReflectPoint pt1=new ReflectPoint(3,5);
Field fieldY= pt1.getClass().getField("y");//共有类型用getField()
//fieldY不是某个对象身上的变量,而是类上,要用它去取某个对象上对应的值
System.out.println(fieldY);
System.out.println(fieldY.get(pt1));
Field fieldX= pt1.getClass().getDeclaredField("x");//私有类型用getDeclaredField()
fieldX.setAccessible(true);
System.out.println(fieldX.get(pt1));
public class ReflectPoint {
private int x;
public int y;
public String str1="ball";
private String str2="basketball";
public String str3="itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString(){
return str1+":"+str2+":"+str3;
}
}
输出
public int cn.itcast.day1.ReflectPoint.y
5
3
函数的反射
Method methodCharAt= String.class.getMethod("charAt", int.class);
System.out.println(methodCharAt.invoke(str, 1));
System.out.println(methodCharAt.invoke(str, new Object[]{2}));
构造函数的反射
String startClassName=args[0];
Method mainMethod=Class.forName(startClassName).getMethod("main",String[].class);
mainMethod.invoke(null, new Object[]{new String[]{"111","222","333"}});
mainMethod.invoke(null, (Object)new String[]{"111","222","333"});
输出:
b
c
111
222
333
编写一个函数 传进一个对象,如果这个对象的String类型的变量里有含有b则用 a替换
private static void changeStringValue(Object obj) throws Exception {
// TODO Auto-generated method stub
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);
}
}
}
public class ReflectPoint {
private int x;
public int y;
public String str1="ball";
private String str2="basketball";
public String str3="itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString(){
return str1+":"+str2+":"+str3;
}
changeStringValue(pt1);
System.out.println(pt1);
输出:
aall:basketball:itcast
这个方法只能替换 public类型的String变量,如果是private 则不能获得变量的值,无法替换;私有类型用getDeclaredField()