Person p = new Person();
1.Class c = String.class;
2.Class c = p.getClass();
3.Class c = Class.forName("java.lang.String");//throw exception
Person p = (Person)c.newInstance();
package com.hoo.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestReflect {
public static void main(String[] args) throws Exception {
String str = "abc";
Class c1 = str.getClass();
Class c2 = String.class;
Class c3 = null;
c3 = Class.forName("java.lang.String");
System.out.println(c1 == c2);// true
System.out.println(c1 == c3);// true
System.out.println(c1.isPrimitive());// false //判断是否基本数据类型
System.out.println(int.class.isPrimitive());// true
System.out.println(int.class == Integer.class);// false
System.out.println(int.class == Integer.TYPE);// true
System.out.println(int[].class.isPrimitive());// false
System.out.println(int[].class.isArray());// true
/*
* Constructor
*/
Constructor<?>[] cs = String.class.getDeclaredConstructors();
// String.class.getConstructors(); 只能访问public
for (Constructor c : cs) {
c.setAccessible(true);
System.out.println(c);
}
System.out.println(String.class.getConstructor(String.class));
/*
* Method
*/
Method[] ms = String.class.getDeclaredMethods();
for (Method m : ms) {
// String s = Modifier.toString(m.getModifiers()); //public private default protected
m.setAccessible(true);
System.out.println(m);
}
/*
* Field
*/
Field[] fs = String.class.getDeclaredFields();
for (Field f : fs) {
f.setAccessible(true);
System.out.println(f);
}
}
}
package com.hoo.reflect;
import java.lang.reflect.Field;
public class TestReflect2 {
public static void main(String[] args) throws Exception {
RefletPoint rp = new RefletPoint(3, 4);
changeBtoA(rp);
System.out.println(rp);
}
private static void changeBtoA(Object obj) throws Exception{
Field[] fs = obj.getClass().getDeclaredFields();
for(Field f : fs){
f.setAccessible(true);
if(f.getType() == String.class){
String oldValue = (String)f.get(obj);
String newValue = oldValue.replace('b', 'a');
f.set(obj, newValue);
}
}
}
}
class RefletPoint {
private int x = 0;
public int y = 0;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcat";
public RefletPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "ReflectPoint [str1 = " + str1 + " ,str2 = " + str2 + " ,str3 = " + str3 + "]";
}
}
package com.hoo.reflect;
import java.lang.reflect.Method;
public class TestReflect3 {
public static void main(String[] args) throws Exception {
Class c = Class.forName("com.hoo.reflect.S");
System.out.println(c.isInstance(new Integer(10)));
System.out.println(c.isInstance(new S()));
String s = "asdf";
Method m = String.class.getMethod("charAt", int.class);
Object ch = m.invoke(s, 3);
System.out.println(ch);
// System.out.println(m.invoke(s, new Object[]{2}));
}
}
class S{
}