/*反射,就是对类的抽象,把类的属性提取出来,是对抽象的抽象。
这里简单的练习一下。
*/
package reflect;
import java.lang.reflect.*;
public class ConstructorReflect {
public static void main(String[] args) throws Exception {
//反射练习
//ReflectDemo();
//替换某类字符串类型字段中某个字符
//StringReplace(); 与以下用反射调用相同
// Method method = ConstructorReflect.class.getMethod("StringReplace", null);
// method.invoke(null, null);
Object[] objs = new Object[] {"String", 2};
System.out.println(objs.getClass().getName());
//反射调用其他类的main方法
// String className = "awt_net.MyQQTest";
// mainInvoke(className);
}
public static void mainInvoke(String className) throws Exception{
//获取将要被执行主方法的类的字节码文件
Class<?> beInvoke = Class.forName(className);
//获取main方法
Method method = beInvoke.getMethod("main", String[].class);
//调用方法,注意参数的形式
method.invoke(null, new Object[] { new String[] {}});
}
public static void StringReplace() throws Exception{
MyString myString = new MyString();
//获取该类中的字段
Field[] fields = MyString.class.getDeclaredFields();
//遍历访问字段
for(Field field : fields){
if(field.getType() == String.class){
field.setAccessible(true); //访问私有字段
String oldValue = (String)field.get(myString);
String newValue = oldValue.replace("e", "d");
field.set(myString, newValue);
}
}
System.out.println(myString);
}
public static void ReflectDemo() throws Exception{
//获取字符串构造器对象
Constructor<String> constructor = String.class.getConstructor(char[].class);
char[] chars = new char[] {'a', 'b', 'c'};
//用字符串构造器对象创建实例
String str = constructor.newInstance(chars);
System.out.println(str);
//获取字符串方法对象
Method method = String.class.getMethod("charAt", int.class);
System.out.println(method.invoke("oh,no", 2));
//获取Point类的字段
Field fieldy = Point.class.getField("y");
System.out.println(fieldy.get(new Point(3, 5)));
Field fieldx = Point.class.getDeclaredField("x");
fieldx.setAccessible(true);
System.out.println(fieldx.get(new Point(5, 1)));
}
}
//简单的练习用类
class Point{
private int x;
public int y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
//简单的练习用类
class MyString{
public int x;
public String hashset = "hashset";
private String treeset = "treeset";
@Override
public String toString() {
return "MyString [hashset=" + hashset + ", treeset=" + treeset + "]";
}
}